-
Notifications
You must be signed in to change notification settings - Fork 3
/
LnPAL3.cpp
797 lines (722 loc) · 18.9 KB
/
LnPAL3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/*
* Copyright 2021-2024 Rochus Keller <mailto:[email protected]>
*
* This file is part of the Luon runtime library.
*
* The following is the license that applies to this copy of the
* file. For a license to use the file under conditions
* other than those described here, please email to [email protected].
*
* This file may be used under the terms of the GNU Lesser
* General Public License version 2.1 or version 3 as published by the Free
* Software Foundation and appearing in the file LICENSE.LGPLv21 and
* LICENSE.LGPLv3 included in the packaging of this file. Please review the
* following information to ensure the GNU Lesser General Public License
* requirements will be met: https://www.gnu.org/licenses/lgpl.html and
* http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
*/
// Adopted from Smalltalk StDisplay.cpp
#include "LnPAL3.h"
#include <QFile>
#include <QPainter>
#include <stdint.h>
#include <QtDebug>
#include <QBitmap>
#include <QMessageBox>
#include <QApplication>
#include <QCloseEvent>
#include <QShortcut>
#include <QClipboard>
#include <bitset>
#include <time.h>
using namespace St;
#define _USE_BB_IMP_
static Display* s_inst = 0;
bool Display::s_run = true;
bool Display::s_break = false;
bool Display::s_copy = false;
QList<QFile*> Display::s_files;
static const int s_msPerFrame = 20; // 20ms according to BB
enum { whitePixel = 1, blackPixel = 0 };
static QFile s_out("st.log");
static inline quint32 tick()
{
static clock_t start = 0;
if( start == 0 )
start = clock();
clock_t t = clock();
return ((double)(t - start) * 1000) / CLOCKS_PER_SEC;
}
Display::Display(QWidget *parent) : QWidget(parent),d_curX(-1),d_curY(-1),d_capsLockDown(false),
d_shiftDown(false),d_recOn(false),d_forceClose(false)
{
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
setCursor(Qt::BlankCursor);
setWindowTitle( renderTitle() );
show();
d_lastEvent = 0;
new QShortcut(tr("ALT+R"), this, SLOT(onRecord()) );
new QShortcut(tr("ALT+L"), this, SLOT(onLog()) );
new QShortcut(tr("ALT+X"), this, SLOT(onExit()) );
new QShortcut(tr("ALT+B"), this, SLOT(onBreak()) );
new QShortcut(tr("ALT+V"), this, SLOT(onPaste()) );
new QShortcut(tr("ALT+SHIFT+V"), this, SLOT(onPasteBenchmark()) );
new QShortcut(tr("ALT+C"), this, SLOT(onCopy()) );
}
Display::~Display()
{
s_inst = 0;
foreach( QFile* f, s_files )
delete f;
s_files.clear();
}
Display*Display::inst()
{
if( s_inst == 0 )
{
s_inst = new Display();
s_run = true;
}
return s_inst;
}
void Display::forceClose()
{
if( s_inst )
{
s_inst->d_forceClose = true;
s_inst->close();
}
}
void Display::setBitmap(const Bitmap& buf)
{
d_bitmap = buf;
d_screen = QImage( buf.width(), buf.height(), QImage::Format_RGB32 );
d_bitmap.toImage(d_screen);
d_updateArea = QRect();
setFixedSize( buf.width(), buf.height() );
update();
}
void Display::setCursorBitmap(const Bitmap& bm)
{
QImage cursor( bm.width(), bm.height(), QImage::Format_RGB32 );
bm.toImage(cursor);
QBitmap pix = QPixmap::fromImage( cursor );
setCursor( QCursor( pix, pix, 0, 0 ) );
// update();
}
void Display::setCursorPos(qint16 x, qint16 y)
{
d_curX = x;
d_curY = y;
update();
}
void Display::drawRecord(int x, int y, int w, int h)
{
if( !d_recOn )
return;
QPainter p(&d_record);
if( w < 0 || h < 0 )
p.setPen(Qt::red);
else
p.setPen(Qt::green);
p.drawRect(x,y,w,h);
}
void Display::updateArea(const QRect& r )
{
d_updateArea |= r;
}
void Display::setLog(bool on)
{
if( on && !s_out.isOpen() )
onLog();
else if( !on && s_out.isOpen() )
onLog();
}
void Display::processEvents()
{
Display::inst()->updateImage();
QApplication::processEvents();
}
void Display::copyToClipboard(const QByteArray& str)
{
QString text = QString::fromUtf8(str);
text.replace( '\r', '\n' );
QApplication::clipboard()->setText( text );
}
void Display::onRecord()
{
if( !d_recOn )
{
qWarning() << "record on";
d_recOn = true;
d_record = d_screen.convertToFormat(QImage::Format_RGB32);
}else
{
qWarning() << "record off";
d_record.save("record.png");
d_record = QImage();
d_recOn = false;
}
}
void Display::onExit()
{
exit(0);
}
void Display::onLog()
{
if( s_out.isOpen() )
{
qWarning() << "logging off";
s_out.close();
}else if( s_out.open(QIODevice::WriteOnly) )
{
qWarning() << "logging on";
}else
qCritical() << "ERROR: cannot open log for writing";
}
void Display::onBreak()
{
if( s_break )
return;
s_break = true;
qWarning() << "break started";
}
void Display::onPaste()
{
const QByteArray text = QApplication::clipboard()->text().toLatin1();
for( int i = 0; i < text.size(); i++ )
{
simulateKeyEvent(text[i]);
}
}
void Display::onCopy()
{
s_copy = true;
}
void Display::onPasteBenchmark()
{
QFile in(":/benchmark/Benchmark.st");
if( in.open(QIODevice::ReadOnly) )
{
const QByteArray text = in.readAll();
for( int i = 0; i < text.size(); i++ )
{
simulateKeyEvent(text[i]);
}
}
}
void Display::paintEvent(QPaintEvent* event)
{
if( d_bitmap.isNull() )
return;
const QRect r = event->rect();
if( r.isNull() )
return;
QPainter p(this);
p.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, false );
p.drawImage( r,d_screen, r);
}
void Display::timerEvent(QTimerEvent*)
{
// update();
}
void Display::closeEvent(QCloseEvent* event)
{
if( d_forceClose || !s_run )
{
event->accept();
deleteLater();
return;
}
event->ignore();
const int res = QMessageBox::warning(this, renderTitle(), tr("Do you really want to close the VM? Changes are lost!"),
QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel );
if( res == QMessageBox::Ok )
s_run = false;
}
void Display::mouseMoveEvent(QMouseEvent* event)
{
QPoint old = d_mousePos;
d_mousePos = event->pos();
if( d_mousePos.x() < 0 )
d_mousePos.setX(0);
if( d_mousePos.y() < 0 )
d_mousePos.setY(0);
if( d_mousePos.x() >= width() )
d_mousePos.setX( width() - 1 );
if( d_mousePos.y() >= height() )
d_mousePos.setY( height() - 1 );
const quint32 diff = tick() - d_lastEvent;
if( diff < s_msPerFrame )
return;
if( old.x() != d_mousePos.x() )
{
if( d_mousePos.x() > MaxPos )
postEvent( XLocation, MaxPos );
else
postEvent( XLocation, d_mousePos.x() );
}
if( old.y() != d_mousePos.y() )
{
if( d_mousePos.y() > MaxPos )
postEvent( YLocation, MaxPos );
else
postEvent( YLocation, d_mousePos.y() );
}
}
enum MousButton { LeftButton = 130,
MidButton = 128, // BB error, mixed up 129 and 128, VIM fixed
RightButton = 129
};
void Display::mousePressEvent(QMouseEvent* event)
{
mousePressReleaseImp( true, event->button() );
}
void Display::mouseReleaseEvent(QMouseEvent* event)
{
mousePressReleaseImp( false, event->button() );
}
void Display::mousePressReleaseImp(bool press, int button)
{
const EventType t = press ? BiStateOn : BiStateOff;
switch( button )
{
case Qt::LeftButton:
if( QApplication::keyboardModifiers() == 0 )
postEvent( t, LeftButton );
else if( QApplication::keyboardModifiers() == Qt::ControlModifier )
postEvent( t, RightButton );
else if( QApplication::keyboardModifiers() == ( Qt::ControlModifier | Qt::ShiftModifier ) )
postEvent( t, MidButton );
break;
case Qt::RightButton:
if( QApplication::keyboardModifiers() == Qt::ShiftModifier )
postEvent( t, MidButton );
else
postEvent( t, RightButton );
break;
case Qt::MidButton:
postEvent( t, MidButton );
break;
default:
break;
}
}
void Display::keyPressEvent(QKeyEvent* event)
{
//qDebug() << "keyPressEvent" << QByteArray::number(event->key(),16).constData() << event->text();
char ch = 0;
if( !event->text().isEmpty() )
ch = event->text()[0].toLatin1();
if( !keyEvent( event->key(), ch, true ) )
QWidget::keyPressEvent(event);
}
void Display::keyReleaseEvent(QKeyEvent* event)
{
char ch = 0;
if( !event->text().isEmpty() )
ch = event->text()[0].toLatin1();
if( !keyEvent( event->key(), ch, false ) )
QWidget::keyReleaseEvent(event);
}
void Display::inputMethodEvent(QInputMethodEvent* event)
{
QString text = event->commitString();
if( !text.isEmpty() && text.at(0).isPrint() )
{
const char ch = text.at(0).toLatin1();
keyEvent( 0, ch, true );
keyEvent( 0, ch, false );
}
}
QString Display::renderTitle() const
{
return QString("%1 v%2").arg( QApplication::applicationName() ).arg( QApplication::applicationVersion() );
}
static inline quint16 compose( quint8 t, quint16 p )
{
return (quint16)t << 12 | p;
}
bool Display::postEvent(Display::EventType t, quint16 param, bool withTime )
{
Q_ASSERT( t >= XLocation && t <= BiStateOff );
if( withTime )
{
const quint32 time = tick();
const quint32 diff = time - d_lastEvent;
d_lastEvent = time;
if( diff <= MaxPos )
{
d_events.enqueue( compose( DeltaTime, diff ) );
notify();
}else
{
d_events.enqueue( compose( AbsoluteTime, 0 ) );
notify();
d_events.enqueue( ( time >> 16 ) & 0xffff);
notify();
d_events.enqueue( time & 0xffff );
notify();
}
}
d_events.enqueue( compose( t, param ) );
notify();
return true;
}
/*
// Alto keyboard layout
// see https://www.extremetech.com/wp-content/uploads/2011/10/Alto_Mouse_c.jpg
1 !
2 @
3 #
4 $
5 %
6 ~
7 &
8 *
9 (
0 )
- _
= +
\ |
[ {
] }
← ↑
; :
' "
, <
. >
/ ?
a A
...
z Z
*/
static inline char toAltoUpper( char ch )
{
switch( ch )
{
case '+':
return '='; // means: the key is labeled with '=' for normal press and '+' for shift press
// if we want a '+' to appear we have to send shift-down '=' shift-up to the VM
case '_':
return '-';
case '|':
return '\\';
case '{':
return '[';
case '}':
return ']';
case ':':
return ';';
case '"':
return '\'';
case '<':
return ',';
case '>':
return '.';
case '?':
return '/';
case '!':
return '1';
case '@':
return '2';
case '#':
return '3';
case '$':
return '4';
case '%':
return '5';
case '~':
return '6';
case '&':
return '7';
case '*':
return '8';
case '(':
return '9';
case ')':
return '0';
}
if( ch >= 'A' && ch <= 'Z' )
return ::tolower(ch);
return 0;
}
static inline bool isAltoLower(char ch )
{
if( ( ch >= 'a' && ch <= 'z' ) || ( ch >= '0' && ch <= '9' ) )
return true;
switch( ch )
{
case '-':
case '=':
case '\\':
case '[':
case ']':
case ';':
case '\'':
case ',':
case '.':
case '/':
return true;
}
return false;
}
bool Display::keyEvent(int keyCode, char ch, bool down)
{
//qDebug() << QByteArray::number(keyCode,16).constData() << ch;
switch( keyCode )
{
case Qt::Key_Backspace:
return postEvent( down ? BiStateOn : BiStateOff, 8 );
case Qt::Key_Tab:
return postEvent( down ? BiStateOn : BiStateOff, 9 );
// NOTE: line feed 10 not supported
case Qt::Key_Return:
return postEvent( down ? BiStateOn : BiStateOff, 13 );
case Qt::Key_Escape:
return postEvent( down ? BiStateOn : BiStateOff, 27 );
case Qt::Key_Space:
return postEvent( down ? BiStateOn : BiStateOff, 32 );
case Qt::Key_Delete:
return postEvent( down ? BiStateOn : BiStateOff, 127 );
// NOTE: right shift 137
case Qt::Key_Shift:
d_shiftDown = down;
return postEvent( down ? BiStateOn : BiStateOff, 136 );
case Qt::Key_Control:
return postEvent( down ? BiStateOn : BiStateOff, 138 );
case Qt::Key_CapsLock:
d_capsLockDown = down;
return postEvent( down ? BiStateOn : BiStateOff, 139 );
case Qt::Key_Left:
// ← ASCII 95 0x5f _
return postEvent( down ? BiStateOn : BiStateOff, 95 );
case Qt::Key_Up:
// ↑ ASCII 94 0x5e ^
return postEvent( down ? BiStateOn : BiStateOff, 94 );
}
if( ch >= '!' && ch <= '~' )
{
if( isAltoLower( ch ) )
{
if( down )
sendShift( true, false );
const bool res = postEvent( down ? BiStateOn : BiStateOff, ch );
if( !down )
sendShift( false, false );
return res;
}else if( ( ch = toAltoUpper( ch ) ) )
{
if( down )
sendShift( true, true );
const bool res = postEvent( down ? BiStateOn : BiStateOff, ch );
if( !down )
sendShift( false, true );
return res;
}
}
return false;
}
void Display::simulateKeyEvent(char ch)
{
switch( ch )
{
case ' ':
keyEvent(Qt::Key_Space,0,true);
keyEvent(Qt::Key_Space,0,false);
return;
case '\n':
keyEvent(Qt::Key_Return,0,true);
keyEvent(Qt::Key_Return,0,false);
return;
case '\r':
return;
case 0x08:
keyEvent(Qt::Key_Backspace,0,true);
keyEvent(Qt::Key_Backspace,0,false);
return;
case 0x09:
keyEvent(Qt::Key_Tab,0,true);
keyEvent(Qt::Key_Tab,0,false);
return;
case 0x1b:
keyEvent(Qt::Key_Escape,0,true);
keyEvent(Qt::Key_Escape,0,false);
return;
}
keyEvent(0,ch,true);
keyEvent(0,ch,false);
}
void Display::sendShift(bool keyPress, bool shiftRequired)
{
if( shiftRequired && !d_shiftDown ) // need to press shift
postEvent( keyPress ? BiStateOn : BiStateOff, 136 );
else if( !shiftRequired && d_shiftDown ) // need to release shift
postEvent( !keyPress ? BiStateOn : BiStateOff, 136 );
}
void Display::notify()
{
emit sigEventQueue();
}
void Display::updateImage()
{
#if 1
if( !d_updateArea.isNull() )
{
// qWarning() << "updateArea" << d_updateArea;
d_bitmap.toImage( d_screen, d_updateArea );
update( d_updateArea );
d_updateArea = QRect();
}
#else
d_bitmap.toImage( d_screen, d_screen.rect() );
update(d_screen.rect());
#endif
}
Bitmap::Bitmap(quint8* buf, quint16 wordLen, quint16 pixWidth, quint16 pixHeight)
{
d_buf = buf;
d_wordLen = wordLen; // number of words (16 bit) in buffer
d_pixWidth = pixWidth;
d_pixHeight = pixHeight;
d_pixLineWidth = ( ( pixWidth + PixPerWord - 1 ) / PixPerWord ) * PixPerWord;
// d_pixLineWidth is the d_pixWidth possibly extended by a few pixels so that d_pixLineWidth % 16 = 0
Q_ASSERT( d_pixLineWidth * d_pixHeight / 16 == d_wordLen );
}
void Bitmap::toImage(QImage& img, QRect area) const
{
if( isNull() )
return;
Q_ASSERT( img.format() == QImage::Format_RGB32 // The image is stored using a 32-bit RGB format (0xffRRGGBB).
&& img.width() == d_pixWidth && img.height() == d_pixHeight );
// more efficient than Mono because the Qt pipeline has to convert it otherwise
if( area.isNull() )
area = img.rect();
else
{
Q_ASSERT( area.x() >= 0 && ( area.x() + area.width() ) <= d_pixWidth );
Q_ASSERT( area.y() >= 0 && ( area.y() + area.height() ) <= d_pixHeight );
}
const int sw = d_pixLineWidth / 8;
const int dw = img.bytesPerLine();
const uchar *src_data = d_buf;
uchar *dest_data = img.bits();
const int ax = area.x();
const int aw = area.width();
const int axaw = ax + aw;
const int ah = area.height();
const int ay = area.y();
src_data += sw * ay;
dest_data += dw * ay;
for( int y = 0; y < ah; y++ )
{
uint*p = (uint*)dest_data;
p += ax;
for( int x = ax; x < axaw; x++ )
{
int v = ((src_data[x>>3] >> (7 - (x & 7))) & 1);
if( v )
*p++ = 0xff000000;
else
*p++ = 0xffffffff;
}
src_data += sw;
dest_data += dw;
}
}
extern "C" {
#ifdef _WIN32
#define DllExport __declspec(dllexport)
#else
#define DllExport
#endif
DllExport void PAL3_setIdle(void (*tick)() )
{
// NOP
}
DllExport int PAL3_init(uint8_t* b, int len, int w, int h)
{
Bitmap bm(b, len / 2, w, h);
Display::inst()->setBitmap(bm);
return 1;
}
DllExport int PAL3_deinit()
{
Display::inst()->forceClose();
return 0;
}
DllExport int PAL3_setCursorBitmap(uint8_t* b, int w, int h)
{
Bitmap bm(b, (w * h) / (2 * 8), w, h);
Display::inst()->setCursorBitmap(bm);
return 1;
}
DllExport void PAL3_setCursorPos(int x, int y)
{
Display::inst()->setCursorPos(x,y);
}
DllExport int PAL3_processEvents(int sleep)
{
Display::processEvents();
if( !Display::s_run )
return -1;
else
return Display::inst()->eventsPending();
}
DllExport int PAL3_nextEvent()
{
if( Display::inst()->eventsPending() )
{
const quint16 e = Display::inst()->nextEvent();
#if 0
static int count = 0;
if( count )
{
qWarning() << "cpp AbsoluteTime word" << 3-count;
count--;
}else
{
QByteArray name;
const quint16 t = e >> 12;
switch(t)
{
case Display::DeltaTime:
name = "DeltaTime";
break;
case Display::XLocation:
name = "XLocation";
break;
case Display::YLocation:
name = "YLocation";
break;
case Display::BiStateOn:
name = "BiStateOn";
break;
case Display::BiStateOff:
name = "BiStateOff";
break;
case Display::AbsoluteTime:
count = 2;
name = "AbsoluteTime";
break;
}
qWarning() << "cpp" << name.constData() << (e & Display::MaxPos) << "pending" << Display::inst()->eventsPending();
}
#endif
return e;
}else
return 0;
}
DllExport int32_t PAL3_getTime()
{
return tick();
}
DllExport void PAL3_updateArea(int x,int y,int w,int h,int cx,int cy,int cw,int ch)
{
const QRect r(x,y,w,h);
const QRect clip(cx,cy,cw,ch);
const QRect patch(r & clip);
Display::inst()->updateArea( patch );
}
}