-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkeyboard.c
2243 lines (2048 loc) · 83.2 KB
/
keyboard.c
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** This file is part of the Matrix Brandy Basic VI Interpreter.
** Copyright (C) 2000-2014 David Daniels
** Copyright (C) 2006, 2007 Colin Tuckley
** Copyright (C) 2014 Jonathan Harston
** Copyright (C) 2018-2024 Michael McConnell, Jonathan Harston and contributors
**
** Brandy is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2, or (at your option)
** any later version.
**
** Brandy is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Brandy; see the file COPYING. If not, write to
** the Free Software Foundation, 59 Temple Place - Suite 330,
** Boston, MA 02111-1307, USA.
**
**
** This file contains the keyboard handling routines.
**
** When running under operating systems other than RISC OS the
** interpreter uses its own keyboard handling functions to
** provide both line editing and a line recall feature
**
**
** 20th August 2002 Crispian Daniels:
** Included Mac OS X target in conditional compilation.
**
** December 2006 Colin Tuckley:
** Rewrite to use SDL library Event handling.
**
** 06-Mar-2014 JGH: Zero-length function key strings handled correctly.
** 13-Nov-2018 JGH: SDL INKEY-1/2/3 checks for either modifier key.
** Bug: Caps/Num returns lock state, not key state.
** 03-Dec-2018 JGH: SDL wasn't detecting DELETE. Non-function special
** keys modified correctly.
** 04-Dec-2018 JGH: set_fn_string checks if function key in use.
** Some tidying up before deeper work.
** 07-Dec-2018 JGH: get_fn_string returns function key string for *SHOW.
** Have removed some BODGE conditions.
** 11-Dec-2018 JGH: Gradually moving multiple emulate_inkey() functions into
** one kbd_inkey() function. First result is that all platforms
** now support INKEY-256 properly.
** kbd_inkey(): -256: all platforms
** +ve: RISCOS:ok, WinSDL:ok, MGW:ok, DJP:ok
** -ve: RISCOS:ok, WinSDL:ok, MGW:ok, DJP:to do
** Credit: con_keyscan() from JGH 'console' library
** 27-Dec-2018 JGH: DOS target can detect Shift/Ctrl/Alt as that's the only DOS API.
** 28-Dec-2018 JGH: kbd_init(), kbd_quit() all consolidated.
** 05-Jan-2019 JGH: kbd_fnkeyget(), kbd_fnkeyset().
** 06-Jan-2019 JGH: Started on kbd_readline().
** 17-Jan-2019 JGH: Merged common MinGW and DJGPP kbd_get() code. Modifiers fully
** work with non-function special keys. Some temporary scaffolding
** in readline().
** Tested on: MinGW
** 27-Jan-2019 JGH: Unix build works again, missed a #ifdef block.
** Tested on: DJGPP, MinGW, WinSDL, CentOS, RISCOS.
** 25-Aug-2019 JGH: Started stipping out legacy code.
** Tested on: DJGPP, MinGW, WinSDL, CentOS.
** RISCOS builds, but other issues cause problems.
** 28-Aug-2019 JGH: Cut out a lot of old code, added some more documentation.
** Corrected some errors in dostable[] with PgUp/PgDn/End.
** Corrected low level top-bit codes returned from SDL key read.
** Low-level keycode doesn't attempt to expand soft keys, read
** EXEC file or input redirection, that's kbd_get()'s responsibility.
** kbd_modkeys() obeys its API.
** Tested on: DJGPP, MinGW, WinSDL, CentOS.
** RISCOS builds, but other issues cause problems.
** 29-Aug-2019 JGH: Stopped kbd_get0() returning &00 when keypress returns nothing.
** Found a couple of obscure errors in dostable[] translation.
** 30-Aug-2019 JGH: Testing, minor bugs in BBC/JP keyboard layout. US/UK all ok.
** Some builds don't "see" Print/Pause/Width. SDL only one that sees Print.
** 07-Sep-2019 JGH: Last bits of emulate_get() now migrated into kbd_get0(). Loads of
** redundant code removed. Escape processing moving into here.
** *FX229 tested: DJGPP, MinGW, WinSDL, CentOS/SDL
** *FX220 starting to work, escpoll() and SIGINT check physical key, needs
** to check character.
** 14-Sep-2019 JGH: ANSI keypresses working again. Amputated entirety of decode_sequence(),
** replaced with parsing code from JGH Console library. Needs negative
** INKEY code for Unix+NoSDL.
** 25-Sep-2019 JGH: Moved all Escape polling into here, solves EscapeEscape problems on non-SDL.
** Escape setting checks sysvars, character input checks sv_EscapeChar.
** Background Escape still checks physical key.
** 28-Sep-2019 JGH: WinDJPP: CHR$27=Esc, CHR$3=null, CtrlBreak=null, no EscEsc
** WinMinGW: CHR$27=Esc, CHR$3=Esc, CtrlBreak=Quit, EscEsc fixed
** WinSDL: CHR$27=Esc, CHR$3=null, CtrlBreak=null, EscEsc fixed
** WinSDL loses some keypresses
** probably background and foreground Escape checking clashing
** cf cZ80Tube and PDPTube.
** UnixSDL: CHR$27=Esc, CHR$3=null, CtrlBreak=null, no EscEsc
** UnixSDL doesn't seem to lose keypresses
** tbrandy: CHR$27=null, CHR$3=Esc, CtrlBreak=null, no EscEsc
** sbrandy: CHR$27=null, CHR$3=Esc, CtrlBreak=null, no EscEsc
**
** 07-Oct-2019 JGH: Background Escape polling disabled during foreground key polling.
** Prevents lost keypresses during input.
**
** Issues: Alt+alphanum gives &180+n instead of &080+n.
** A few outstanding bugs in BBC/JP keyboard layout.
** To do: Implementing *FX225,etc will resolve raw/cooked keycode issue, cf below.
**
** Note: This is the only file that tests for BEOS.
**
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "target.h"
#ifdef TARGET_OPENBSD
#include <sys/select.h>
#endif
#include "common.h"
#include "basicdefs.h"
#include "errors.h"
#include "screen.h"
#include "keyboard.h"
#include "inkey.h"
#include "miscprocs.h"
#include "mos.h"
#ifdef TARGET_SUNOS
#include <sys/filio.h>
#endif
#ifdef USE_SDL
#include "graphsdl.h"
extern threadmsg tmsg;
#endif
#ifdef TARGET_RISCOS
/* New keyboard routines */
/* --------------------- */
#include "kernel.h"
#include "swis.h"
#include "errno.h"
/* Veneers, fill in later */
boolean kbd_init() { return TRUE; }
int kbd_setfkey(int key, char *string, int length) {
return set_fn_string(key, string, length); }
char *kbd_getfkey(int key, int *len) {
return get_fn_string(key, len); }
readstate kbd_readln(char buffer[], int32 length, int32 echochar) {
return emulate_readline(&buffer[0], length, echochar); }
/* kbd_inkey called to implement Basic INKEY and INKEY$ functions */
/* -------------------------------------------------------------- */
int32 kbd_inkey(int32 arg) {
// RISC OS, pass directly to MOS
// -----------------------------
_kernel_oserror *oserror;
_kernel_swi_regs regs;
if (arg == -256) return OSVERSION;
regs.r[0] = 129; /* Use OS_Byte 129 for this */
regs.r[1] = arg & BYTEMASK;
regs.r[2] = (arg>>BYTESHIFT) & BYTEMASK;
oserror = _kernel_swi(OS_Byte, ®s, ®s);
if (oserror != NIL) {
error(ERR_CMDFAIL, oserror->errmess);
return -1;
}
if (regs.r[2] == 0) return regs.r[1]; /* Character was read successfully */
else return -1; /* Timed out */
}
int32 kbd_inkey256() {
// RISC OS, pass directly to MOS
// -----------------------------
_kernel_oserror *oserror;
_kernel_swi_regs regs;
int32 arg = -256;
regs.r[0] = 129; /* Use OS_Byte 129 for this */
regs.r[1] = arg & BYTEMASK;
regs.r[2] = (arg>>BYTESHIFT) & BYTEMASK;
oserror = _kernel_swi(OS_Byte, ®s, ®s);
if (oserror != NIL) {
error(ERR_CMDFAIL, oserror->errmess);
return -1;
}
if (regs.r[2] == 0) return regs.r[1]; /* Character was read successfully */
else return -1; /* Timed out */
}
/* kbd_get called to implement Basic GET and GET$ functions */
/* -------------------------------------------------------- */
int32 kbd_get() {
// RISC OS, pass directly to MOS
// -----------------------------
_kernel_oserror *oserror;
_kernel_swi_regs regs;
oserror = _kernel_swi(OS_ReadC, ®s, ®s);
if (oserror != NIL) error(ERR_CMDFAIL, oserror->errmess);
return regs.r[0];
}
/* ================================================================= */
/* ================= RISC OS versions of functions ================= */
/* ================================================================= */
#include "kernel.h"
#include "swis.h"
/*
** 'emulate_get' emulates the Basic function 'get'
*/
int32 emulate_get(void) {
return _kernel_osrdch();
}
/*
** 'emulate_inkey' does the hard work for the Basic 'inkey' function
*/
int32 emulate_inkey(int32 arg) {
_kernel_oserror *oserror; /* Use OS_Byte 129 to obtain the info */
_kernel_swi_regs regs;
regs.r[0] = 129; /* Use OS_Byte 129 for this */
regs.r[1] = arg & BYTEMASK;
regs.r[2] = (arg>>BYTESHIFT) & BYTEMASK;
oserror = _kernel_swi(OS_Byte, ®s, ®s);
if (oserror != NIL) {
error(ERR_CMDFAIL, oserror->errmess);
return -1;
}
if (arg >= 0) { /* +ve argument = read keyboard with time limit */
if (regs.r[2] == 0) /* Character was read successfully */
return (regs.r[1]);
else if (regs.r[2] == 0xFF) /* Timed out */
return -1;
else {
error(ERR_CMDFAIL, "C library has missed an escape event");
return -1;
}
}
else { /* -ve argument */
if (regs.r[1] == 0xFF)
return -1;
else {
return regs.r[1];
}
}
return 0; /* Not needed, but it keeps the Acorn C compiler happy */
}
/*
** 'emulate_readline' reads a line from the keyboard. It returns 'true'
** if the call worked successfully or 'false' if 'escape' was pressed.
** The data input is stored at 'buffer'. Up to 'length' characters can
** be read. A 'null' is added after the last character. The reason for
** using this function in preference to 'fgets' under RISC OS is that
** 'fgets' does not use 'OS_ReadLine' and therefore bypasses the command
** line history and other features that might be available via this SWI
** call.
*/
readstate emulate_readline(char buffer[], int32 length, int32 echochar) {
_kernel_oserror *oserror;
_kernel_swi_regs regs;
int32 carry;
regs.r[0] = (int32)(&buffer[0]);
regs.r[1] = length-1; /* -1 to allow for a NULL to be added at the end in all cases */
regs.r[2] = 0; /* Allow any character to be input */
regs.r[3] = 255;
oserror = _kernel_swi_c(OS_ReadLine, ®s, ®s, &carry);
if (oserror != NIL) {
error(ERR_CMDFAIL, oserror->errmess);
return READ_EOF;
}
if (carry != 0) /* Carry is set - 'escape' was pressed */
buffer[0] = NUL;
else {
buffer[regs.r[1]] = NUL; /* Number of characters read is returned in R1 */
}
return carry == 0 ? READ_OK : READ_ESC;
}
/*
* set_fn_string - Define a function key string
*/
int set_fn_string(int key, char *string, int length) {
printf("Key = %d String = '%s'\n", key, string);
return 0;
}
char *get_fn_string(int key, int *len) {
return "";
}
void kbd_quit() {
}
int kbd_escack() {
byte tmp=basicvars.escape;
basicvars.escape=FALSE; /* Clear pending Escape */
return tmp ? -1 : 0; /* Return previous Escape state */
}
int kbd_esctest() {
byte result;
result = _kernel_osbyte(229,0,255);
if(0 != result) return FALSE;
result = _kernel_osbyte(200,0,255);
if((result & 1) == 1) return FALSE;
return TRUE;
}
int kbd_escpoll() {
if (kbd_esctest()) if (kbd_inkey(-113)) basicvars.escape=TRUE;
return basicvars.escape;
}
int32 kbd_readline(char *buffer, int32 length, int32 chars) {
// RISC OS, pass directly to MOS
// -----------------------------
_kernel_oserror *oserror;
_kernel_swi_regs regs;
int32 carry;
// RISC OS compiler doesn't like code before variable declaration, so have to duplicate
if (length<1) return 0; /* Filter out impossible or daft calls */
chars=(chars & 0xFF) | 0x00FF2000; /* temp'y force all allowable chars */
regs.r[0] = (int)(&buffer[0]);
regs.r[1] = length - 1; /* Subtract one to allow for terminator */
regs.r[2] = (chars >> 8) & 0xFF; /* Lowest acceptable character */
regs.r[3] = (chars >> 16) & 0xFF; /* Highest acceptable character */
if (regs.r[0] & 0xFF000000) { /* High memory */
regs.r[4] = chars & 0xFF0000FF; /* R4=Echo character and flags */
oserror = _kernel_swi_c(0x00007D, ®s, ®s, &carry); /* OS_ReadLine32 */
/* If OS_ReadLine32 doesn't exist, we don't have high memory anyway, so safe */
} else { /* Low memory */
regs.r[0]=regs.r[0] | (chars & 0xFF000000); /* R0=Flags and address */
regs.r[4]=chars & 0x000000FF; /* R4=Echo character */
oserror = _kernel_swi_c(OS_ReadLine, ®s, ®s, &carry);
}
if (oserror != NIL) {
error(ERR_CMDFAIL, oserror->errmess);
return -1;
}
if (carry) buffer[0] = NUL; /* Carry is set - 'Escape' was pressed */
else buffer[regs.r[1]] = NUL; /* Number of characters returned in R1 */
return carry == 0 ? regs.r[1] : -1; /* To do: -1=READ_ESC */
}
#else /* !TARGET_RISCOS - Matching endif is at end of file */
/* **********************************
* NON RISC OS VERSIONS OF THE CODE *
************************************/
#if defined(TARGET_MINGW) || defined(TARGET_WIN32) || defined(TARGET_BCC32)
#include <windows.h>
#ifdef CYGWINBUILD
#include <fcntl.h>
#endif
#endif
#ifdef TARGET_DJGPP
#include <pc.h>
#include <keys.h>
#include <bios.h>
#include <errno.h>
#include <termios.h>
#endif
#ifdef TARGET_UNIX
#ifdef TARGET_MINIX
#include <sys/time.h>
#endif /* TARGET_MINIX */
// #include <sys/types.h>
#include <errno.h>
// #include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
// Move these later
static struct termios origtty; /* Copy of original keyboard parameters */
#endif /* TARGET_UNIX */
#ifdef USE_SDL
#include "SDL.h"
#include "SDL_events.h"
#include "graphsdl.h"
// Move these later
Uint8 mousestate, *keystate=NULL;
int64 esclast=0;
#endif
#include <stdlib.h>
#if defined(TARGET_MINGW) || defined(TARGET_WIN32) || defined(TARGET_BCC32)
#include <sys/time.h>
#include <sys/types.h>
#ifndef CYGWINBUILD
#include <keysym.h>
#endif
#endif
/* ASCII codes of various useful characters */
#define CTRL_A 0x01
#define CTRL_B 0x02
#define CTRL_C 0x03
#define CTRL_D 0x04
#define CTRL_E 0x05
#define CTRL_F 0x06
#define CTRL_H 0x08
#define CTRL_K 0x0B
#define CTRL_L 0x0C
#define CTRL_N 0x0E
#define CTRL_O 0x0F
#define CTRL_P 0x10
#define CTRL_U 0x15
#define ESCAPE 0x1B
#define DEL 0x7F
/*
** Following are the key codes given in the RISC OS PRMs for the various
** special keys of interest to this program. RISC OS sequences for these
** keys consists of a NUL followed by one of these values. They are used
** internally when processing the keys. The key codes returned by foreign
** operating systems are mapped on to these values where possible.
*/
#define HOME 0x1E
#define CTRL_HOME 0x1E
#define END 0x8B
#define CTRL_END 0xAB
#define UP 0x8F
#define CTRL_UP 0xAF
#define DOWN 0x8E
#define CTRL_DOWN 0xAE
#define LEFT 0x8C
#define CTRL_LEFT 0xAC
#define RIGHT 0x8D
#define CTRL_RIGHT 0xAD
#define PGUP 0x9F
#define CTRL_PGUP 0xBF
#define PGDOWN 0x9E
#define CTRL_PGDOWN 0xBE
#define INSERT 0xCD
#define CTRL_INSERT 0xED
/* DELETE is already defined in MinGW */
#define KEY_DELETE 0x7F
#define CTRL_DELETE 0x7F
/* Function key codes */
#define KEY_F0 0x80
#define SHIFT_F0 0x90
#define CTRL_F0 0xA0
#define KEY_F1 0x81
#define SHIFT_F1 0x91
#define CTRL_F1 0xA1
#define KEY_F2 0x82
#define SHIFT_F2 0x92
#define CTRL_F2 0xA2
#define KEY_F3 0x83
#define SHIFT_F3 0x93
#define CTRL_F3 0xA3
#define KEY_F4 0x84
#define SHIFT_F4 0x94
#define CTRL_F4 0xA4
#define KEY_F5 0x85
#define SHIFT_F5 0x95
#define CTRL_F5 0xA5
#define KEY_F6 0x86
#define SHIFT_F6 0x96
#define CTRL_F6 0xA6
#define KEY_F7 0x87
#define SHIFT_F7 0x97
#define CTRL_F7 0xA7
#define KEY_F8 0x88
#define SHIFT_F8 0x98
#define CTRL_F8 0xA8
#define KEY_F9 0x89
#define SHIFT_F9 0x99
#define CTRL_F9 0xA9
#define KEY_F10 0xCA
#define SHIFT_F10 0xDA
#define CTRL_F10 0xEA
#define KEY_F11 0xCB
#define SHIFT_F11 0xDB
#define CTRL_F11 0xEB
#define KEY_F12 0xCC
#define SHIFT_F12 0xDC
#define CTRL_F12 0xEC
/* holdcount and holdstack are used when decoding ANSI key sequences. If a
** sequence is read that does not correspond to an ANSI sequence the
** characters are stored here so that they can be returned by future calls
** to 'kbd_get0()'. Note that this is a *stack* not a queue.
*/
#if (defined(USE_SDL) && !defined(TARGET_MINGW)) || !defined(USE_SDL)
static int32 keyboard; /* File descriptor for keyboard */
#endif
static int32 holdcount; /* Number of characters held on stack */
static int32 holdstack[8]; /* Hold stack - Characters waiting to be passed back via 'get' */
#define INKEYMAX 0x7FFF /* Maximum wait time for INKEY */
#define WAITTIME 10 /* Time to wait in centiseconds when dealing with ANSI key sequences */
/* fn_string and fn_string_count are used when expanding a function key string.
** Effectively input switches to the string after a function key with a string
** associated with it is pressed.
*/
static char *fn_string; /* Non-NULL if taking chars from a function key string */
static int fn_string_count; /* Count of characters left in function key string */
/* function key strings */
#define FN_KEY_COUNT 16 /* Number of function keys supported (0 to FN_KEY_COUNT-1) */
static struct {int length; char *text;} fn_key[FN_KEY_COUNT];
/* Line editor history */
#define HISTSIZE 1024 /* Size of command history buffer */
#define MAXHIST 20 /* Maximum number of entries in history list */
static int32
place, /* Offset where next character will be added to buffer */
highplace, /* Highest value of 'place' (= number of characters in buffer) */
histindex, /* Index of next entry to fill in in history list */
highbuffer, /* Index of first free character in 'histbuffer' */
recalline; /* Index of last line recalled from history display */
static boolean backgnd_escape=TRUE; /* Escape polled in the background */
static boolean enable_insert; /* TRUE if keyboard input code is in insert mode */
static char histbuffer[HISTSIZE]; /* Command history buffer */
static int32 histlength[MAXHIST]; /* Table of sizes of entries in history buffer */
static int nokeyboard=0;
static int kbd_vikeys=0;
static boolean waitkey(int wait); /* Forward reference */
static int32 pop_key(void); /* Forward reference */
static int32 read_fn_string(void); /* Forward reference */
static int32 switch_fn_string(int32 key); /* Forward reference */
// static int32 decode_sequence(void); /* Forward reference */
#if !defined(USE_SDL) && defined(CYGWINBUILD) /* text-mode build */
static void reinitWinConsole() {
HANDLE hStdin;
DWORD mode;
hStdin = (HANDLE) _get_osfhandle(STDIN_FILENO);
if (GetFileType(hStdin) == FILE_TYPE_CHAR) {
GetConsoleMode(hStdin, &mode);
mode |= (ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT);
SetConsoleMode(hStdin, mode);
_setmode(_fileno(stdin), O_TEXT);
mode &= ~(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT);
SetConsoleMode(hStdin, mode);
_setmode(_fileno(stdin), O_BINARY);
}
return;
}
#endif /* Windows Text-mode under Cygwin */
/* Keyboard initialise and finalise */
/* ================================ */
/* kbd_init() called to initialise the keyboard code
* --------------------------------------------------------------
* Clears the function key strings, checks if stdin is connected
* to the keyboard or not. If it is then the keyboard functions
* are used to read keypresses. If not, then standard C functions
* are used instead, the assumption being that stdin is taking
* input from a file, similar to *EXEC.
*/
boolean kbd_init() {
int n;
/* We do function key processing outselves */
for (n = 0; n < FN_KEY_COUNT; n++) fn_key[n].text = NIL;
fn_string_count = 0;
fn_string = NIL;
/* We provide a line editor */
holdcount = 0;
histindex = 0;
highbuffer = 0;
enable_insert = TRUE;
set_cursor(enable_insert);
#ifdef TARGET_DOSWIN
#ifdef TARGET_DJGPP
// DOS target
// ----------
struct termios tty;
keyboard = fileno(stdin); /* Handle to keyboard */
if (tcgetattr(keyboard, &tty) == 0) return TRUE; /* Keyboard being used */
// if (tcgetattr(fileno(stdin), &tty) == 0) return TRUE; /* Keyboard being used */
/* tcgetattr() returned an error. If the error is ENOTTY then stdin does not point at
** a keyboard and so the program does simple reads from stdin rather than use the custom
** keyboard code. If the error is not ENOTTY then something has gone wrong so we abort
** the program
*/
if (errno != ENOTTY) return FALSE; /* tcgetattr() returned an error we cannot handle */
basicvars.runflags.inredir = TRUE; /* tcgetattr() returned ENOTTY - use C functions for input */
return TRUE;
#else /* !DOS */
// Windows target, little to do
// ----------------------------
#if !defined(USE_SDL) && defined(CYGWINBUILD) /* text-mode build */
reinitWinConsole();
#endif
nokeyboard=0;
return TRUE;
#endif
#endif /* DOSWIN */
#ifdef TARGET_UNIX
// Unix target
// -----------
struct termios tty;
/* Set up keyboard for unbuffered I/O */
keyboard = fileno(stdin);
if (tcgetattr(keyboard, &tty) < 0) { /* Could not obtain keyboard parameters */
// if (tcgetattr(fileno(stdin), &tty) < 0) { /* Could not obtain keyboard parameters */
nokeyboard=1;
/* tcgetattr() returned an error. If the error is ENOTTY then stdin does not point at
** a keyboard and so the program does simple reads from stdin rather than use the custom
** keyboard code.
*/
#ifndef USE_SDL /* if SDL the window can still poll for keyboard input */
if (errno != ENOTTY) return FALSE; /* tcgetattr() returned an error we cannot handle */
basicvars.runflags.inredir = TRUE; /* tcgetattr() returned ENOTTY - use C functions for input */
#endif
return TRUE;
}
/* We are connected to a keyboard, so set it up for unbuffered input */
origtty = tty; /* Preserve original settings for later */
#ifdef TARGET_LINUX
tty.c_lflag &= ~(XCASE|ECHONL|NOFLSH); /* Case off, EchoNL off, Flush off */
#else
tty.c_lflag &= ~(ECHONL|NOFLSH); /* EchoNL off, Flush off */
#endif
tty.c_lflag &= ~(ICANON|ECHO); /* Line editor off, Echo off */
tty.c_iflag &= ~(ICRNL|INLCR); /* Raw LF and CR */
tty.c_cflag |= CREAD; /* Enable reading */
tty.c_cc[VTIME] = 1; /* 1cs timeout */
tty.c_cc[VMIN] = 1; /* One character at a time */
// tty.c_cc[VINTR] = 27; // doing this here stops get0() working and kills tbrandy
if (tcsetattr(keyboard, TCSADRAIN, &tty) < 0) return FALSE;
/* Could not set up keyboard in the way desired */
return TRUE;
#endif /* UNIX */
#ifdef TARGET_AMIGA
// AMIGA target - just turn Console on
// -----------------------------------
rawcon(1);
return TRUE;
#endif /* AMIGA */
}
/* kbd_quit() called to terminate keyboard control on termination */
/* -------------------------------------------------------------- */
void kbd_quit() {
#ifdef TARGET_DOSWIN
// DOS/Windows target, nothing to do
// ---------------------------------
#endif /* DOSWIN */
#ifdef TARGET_UNIX
// Unix target - restore console settings
// --------------------------------------
(void) tcsetattr(keyboard, TCSADRAIN, &origtty);
#endif /* UNIX */
#ifdef TARGET_AMIGA
// AMIGA target - turn console off
// -------------------------------
rawcon(0);
#endif /* AMIGA */
}
/* Test state of keyboard system */
/* ============================= */
/* kbd_buffered() - is there anything in the keyboard buffer - ADVAL(-1) */
/* --------------------------------------------------------------------- */
int32 kbd_buffered() {
int num=0;
#ifdef TARGET_UNIX
ioctl(STDIN_FILENO, FIONREAD, &num); /* Count bytes in keyboard buffer */
#endif
return num;
}
/* kbd_pending() - will the next GET/INKEY fetch something - EOF#0 */
/* --------------------------------------------------------------- */
int32 kbd_pending() {
if (matrixflags.doexec) {
if (!feof(matrixflags.doexec)) return TRUE; /* Still bytes from exec file */
}
if (holdcount) return TRUE; /* Pushed keypresses pending */
if (fn_string_count) return TRUE; /* Soft key being expanded */
return kbd_buffered()!=0; /* Test keyboard buffer */
}
/* kbd_escpoll() - is there a pending Escape state */
/* ----------------------------------------------- */
/* With background keypress processing, this just tests the flag set by the background,
* similar to BIT ESCFLG in other BASICs. However, on some targets we can't see
* keypresses in the background, we don't have an equivalent of SIGINT, so this routine
* also polls the Escape key.
* To do: the Escape key needs to be definable, but in this routine we need the keynumber
* not the character code.
*/
int kbd_escpoll() {
#ifdef USE_SDL
int64 tmp;
#endif
if (backgnd_escape) { /* Only poll when not doing key input */
if (kbd_esctest()) { /* Only poll if Escapes are enabled */
#ifdef USE_SDL
tmp=basicvars.centiseconds;
if (tmp > esclast) {
esclast=tmp;
if (kbd_inkey(-113)) basicvars.escape=TRUE; // Should check key character, not keycode
}
#else
#ifdef TARGET_MINGW
if (GetAsyncKeyState(VK_ESCAPE)) { // Should check key character, not keycode
while (GetAsyncKeyState(VK_ESCAPE)); /* Wait until key not pressed */
basicvars.escape=TRUE;
}
#endif
#endif
}
}
return basicvars.escape; /* Return Escape state */
}
/* kbd_esctest() - set Escape state if allowed */
/* ------------------------------------------- */
int kbd_esctest() {
if (sysvar[sv_EscapeAction]==0) { /* Does Escape key generate Escapes? */
if ((sysvar[sv_EscapeBreak] & 1)==0) { /* Do Escapes set Escape state? */
return TRUE;
}
}
return FALSE;
}
void kbd_escchar(char a, char b) { return; } // set Escape character
void kbd_escset() { basicvars.escape=TRUE; } // set Escape state
void kbd_escclr() { basicvars.escape=FALSE; } // clear Escape state
/* kbd_escack() - acknowledge and clear Escape state */
/* ------------------------------------------------- */
int kbd_escack() {
byte tmp;
tmp=sysvar[sv_EscapeEffect] ^ 0x0f;
if (basicvars.escape == 0) tmp=tmp | (tmp >> 4);
if (tmp & 1) {
if (matrixflags.doexec) { /* Close EXEC file */
fclose(matrixflags.doexec);
matrixflags.doexec=NULL;
}
holdcount=0; /* Cancel pending keypress */
fn_string_count=0; fn_string = NIL; /* Cancel soft key expansion */
#ifdef TARGET_MINGW
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); /* Consume any queued characters */
#endif
purge_keys(); /* Cancel pending keypresses */
// cancel VDU queue
// cancel sounds
}
if (tmp & 4) { }
if (tmp & 8) { }
tmp=basicvars.escape;
basicvars.escape=FALSE; /* Clear pending Escape */
return tmp ? -1 : 0; /* Return previous Escape state */
}
/* kbd_modkeys() - do a fast read of state of modifier keys */
/* -------------------------------------------------------- */
/* Equivalent to the BBC MOS OSBYTE 118/KEYV call
* On entry: arg is a bitmap of modifier keys to test for
* bit<n> tests key<n>
* ie, b0=Shift, b1=Ctrl, b2=Alt, etc.
* Returns: bitmap of keys pressed, as requested
* bit<n> set if key<n> pressed and key<n> was asked for
* ie, kbd_modkeys(3) will test Shift and Ctrl
*
* Currently, only SHIFT tested by SDL for VDU paged scrolling.
*/
int32 kbd_modkeys(int32 arg) {
#ifdef USE_SDL
if (keystate==NULL) return 0; /* Not yet been initialised */
if (keystate[SDLK_LSHIFT] || keystate[SDLK_RSHIFT]) /* Either SHIFT key */
return 1; else return 0;
#endif
return kbd_inkey(-1) & 0x01; /* Just test SHIFT for now */
}
#ifdef TARGET_DJGPP
/* GetAsyncKeyState() is a Windows API call, DOS only has API call to read Shift/Ctrl/Alt.
* ---------------------------------------------------------------------------------------
* So, we fake an API just for those keys, useful for programs that do
* ON ERROR IF INKEY-1 THEN REPORT:END ELSE something else
* If running in DOSBOX on Windows would be able to call Windows API, but simpler to
* just run a Windows target. Somebody with more skill than me could write the code
* to call Windows from DOS to implement this.
*/
//static int32 vecGetAsyncKeyState=0;
int GetAsyncKeyState(int key) {
int y=0;
y=_bios_keybrd(_NKEYBRD_SHIFTSTATUS);
switch (key) {
case VK_SHIFT: y=(y & 0x003); break; /* SHIFT */
case VK_CONTROL: y=(y & 0x004); break; /* CTRL */
case VK_MENU: y=(y & 0x008); break; /* ALT */
case VK_LSHIFT: y=(y & 0x002); break; /* Left SHIFT */
case VK_LCONTROL: y=(y & 0x100); break; /* Left CTRL */
case VK_LMENU: y=(y & 0x200); break; /* Left ALT */
case VK_RSHIFT: y=(y & 0x001); break; /* Right SHIFT */
case VK_RCONTROL: y=(y & 0x400); break; /* Right CTRL */
case VK_RMENU: y=(y & 0x800); break; /* Right ALT */
default: y=0;
}
return (y ? -1 : 0);
}
// __asm__ __volatile__(
// "cld\n"
// "movw %w1, %%ax\n"
// "andw $255, %%ax\n"
// "push %%ax\n"
// "call [vecGetAsyncKeyState]\n"
// "movw %%ax, %w0\n"
// : "=r" (y)
// : "r" (x)
// );
// return y;
#endif
/* Programmable function key functions */
/* =================================== */
/* kbd_fnkeyset() - define a function key string */
/* --------------------------------------------- */
/* Definition is defined by length, so can contain NULs
* Returns: 0 if ok
* <>0 if can't set because key is in use
*/
// kbd_fnkeyset(int key, int length, char *string) {
int kbd_fnkeyset(int key, char *string, int length) {
if (fn_string_count) return fn_string_count; /* Key in use */
if (fn_key[key].text != NIL) free(fn_key[key].text); /* Remove existing definition */
fn_key[key].length = length;
fn_key[key].text = malloc(length); /* Get space for new definition */
if (fn_key[key].text != NIL) memcpy(fn_key[key].text, string, length);
return 0; /* Ok */
}
/* kbd_fnkeyget() - get a function key string for *SHOW */
/* ---------------------------------------------------- */
/* Returns: string which can include NULs
* len updated with length of string
*/
char *kbd_fnkeyget(int key, int *length) {
*length=fn_key[key].length;
return fn_key[key].text;
}
/* kbd_isfnkey() - check if keycode is a function key */
/* -------------------------------------------------- */
/* Returns: <0 if not a RISC OS function key code
* Returns: function key number if a function key
* NB: INSERT is actually function key 13.
*/
int32 kbd_isfnkey(int32 key) {
if (key & 0x100) {
key = key & 0xFF;
if (key >= KEY_F0 && key <= KEY_F9) return key - KEY_F0;
if (key >= KEY_F10 && key <= KEY_F12) return key - KEY_F10 + 10;
if (matrixflags.osbyte4val == 2) {
if ((key >= 0x8B) && (key <= 0x8F)) return (key - 0x80);
}
}
return -1; /* Not a function key */
}
/* switch_fn_string() - Called to switch input to a function key string */
/* -------------------------------------------------------------------- */
/* Returns: first character of the string
*/
static int32 switch_fn_string(int32 key) {
int32 ch;
if (fn_key[key].length == 1) return *fn_key[key].text;
fn_string = fn_key[key].text;
fn_string_count = fn_key[key].length - 1;
ch = *fn_string;
fn_string++;
return ch;
}
/* read_fn_string() - Called when input being taken from a function key string */
/* --------------------------------------------------------------------------- */
/* Returns: the next character in the string
* if last character fetched, fn_string set to NIL
*/
static int32 read_fn_string(void) {
int32 ch;
ch = *fn_string;
fn_string++;
fn_string_count--;
if (fn_string_count == 0) fn_string = NIL; /* Last character read */
return ch;
}
/* Main key input functions */
/* ======================== */
/* kbd_inkey() called to implement Basic INKEY and INKEY$ functions */
/* ---------------------------------------------------------------- */
/* On entry: <&7FFF : wait for centisecond time for 8-bit keypress
* On exit: <0 : escape or timed out (always -1)
* >=0 : 8-bit keypress
*
* On entry: &FF00 : return a value indication the type of host hardware
* &FF80+n : test for BBC keypress n
* &FF00+n : scan for BBC keypress starting from n (rarely implemented)
* &FE00+n : test for DOS/Windows keypress n (extension)
* &FC00+n : test for SDL keypress n (extension)
* On exit: -1 : key pressed
* 0 : key not pressed
*
* On entry: &8000+n : wait for centisecond time for 16-bit keypress (extension)
* On exit: <0 : escape or timed out (always -1)
* >=0 : 16-bit keypress
*
* If unsupported: return 0 (except &FF00+n returns -1 if unsupported)
*/
int32 kbd_inkey(int32 arg) {
arg = arg & 0xFFFF; /* Argument is a 16-bit number */
// Return host operating system
// ----------------------------
if (arg == 0xFF00) return OSVERSION;
// Timed wait for keypress
// -----------------------
if (arg < 0x8000) {
if (basicvars.runflags.inredir /* Input redirected */
|| matrixflags.doexec /* or *EXEC file active */
|| fn_string_count) return kbd_get(); /* or function key active */
if (holdcount > 0) return pop_key() & 0xFF; /* Character waiting so return it */
if (waitkey(arg)) return kbd_get() & 0xFF; /* Wait for keypress and return it */
else return -1; /* Otherwise return -1 for nothing */
// Negative INKEY - scan for keypress
// ----------------------------------
} else {
arg = arg ^ 0xFFFF; /* Convert to keyscan number */
#ifdef USE_SDL
SDL_Event ev;
if (tmsg.bailout != -1) return 0;
while (matrixflags.videothreadbusy) usleep(1000);
matrixflags.noupdate = 1;
int mx, my;
keystate = SDL_GetKeyState(NULL);
mousestate = SDL_GetMouseState(&mx, &my);
while(SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_ALLEVENTS&(~SDL_KEYEVENTMASK))) {
switch(ev.type) {
case SDL_QUIT:
exit_interpreter(EXIT_SUCCESS);
break;
case SDL_MOUSEBUTTONDOWN:
if (ev.button.button == SDL_BUTTON_LEFT) mousebuttonstate |= 4;