-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLuaWinCon.c
More file actions
1931 lines (1582 loc) · 69.1 KB
/
LuaWinCon.c
File metadata and controls
1931 lines (1582 loc) · 69.1 KB
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
/* * * * * * * * * * * * * *
Created February 2012
by Matthew Britton Sessions
Designed for Lua 5.1 and 5.2
Best viewed at 140 columns.
* * * * * * * * * * * * * */
/* * * * * * * * * * * * * * * * *
TABLE OF CONTENTS
Ctrl+f for the given string to
jump to each indicated section.
Includes . . . . . . . . SEC_INC
Library Init Func. . . . SEC_INIT
Exported Library Funcs . SEC_LIB
Uncategorized. . . . . . SECSUB_LIB_UNCAT
Input Functions. . . . . SECSUB_LIB_INPUT
Library Utility Funcs. . SEC_UTIL
Uncategorized. . . . . . SECSUB_UTIL_UNCAT
Coord Functions. . . . . SECSUB_UTIL_CORD
Attrib Functions . . . . SECSUB_UTIL_ATTR
ScreenBuffer Functions . SECSUB_UTIL_SCRB
Input Record Functions . SECSUB_UTIL_INRC
ColorArray Functions . . SECSUB_UTIL_COLARR
Screenbuffer Methods . . SEC_METHS
* * * * * * * * * * * * * * * * */
/* Here for debugging purposes. */
#define lua_print(L, str) \
lua_getglobal(L, "print"); \
lua_pushstring(L, str); \
lua_call(L, 1, 0)
/* SEC_INC */
#include "LuaWinCon.h"
#include "luaW.h"
/* SEC_INIT */
static int RootTableStackIdx; /* Since the RootTable isn't accessible as an upvalue from luaopen_LuaWinCon, we will store its
stack index here, and any function which needs to work with this table which is guaranteed to only be called from within
luaopen_LuaWinCon will refer to its index with the value in this variable. */
int luaopen_LuaWinCon(lua_State *L) {
struct {
HANDLE StandardInput;
HANDLE StandardOutput;
HANDLE StandardError;
} OriginalHandles;
/* Very first thing we're going to do upon starting is to prepare our RootTable, the single shared table which goes into
the upvalues of every function in this library. */
lua_createtable(L, NumberOfRootEntries, 0);
RootTableStackIdx = lua_gettop(L);
/* Next, we'll prepare ourselves a console for use. This may involve creating a new one...allocating a new console
overwrites the STDIN, STDOUT, and STDERR values returned by GetStdHandle. Whether this is a process-wide effect or not,
we're going to play it safe and save these handles first. */
OriginalHandles.StandardInput = GetStdHandle(STD_INPUT_HANDLE);
OriginalHandles.StandardOutput = GetStdHandle(STD_OUTPUT_HANDLE);
OriginalHandles.StandardError = GetStdHandle(STD_ERROR_HANDLE);
/* We'll save them to some upvalues. They aren't used at the moment, but we could very well use them in the future. */
lua_pushlightuserdata(L, OriginalHandles.StandardInput);
lua_rawseti(L, RootTableStackIdx, RE_OriginalSTDIN);
lua_pushlightuserdata(L, OriginalHandles.StandardOutput);
lua_rawseti(L, RootTableStackIdx, RE_OriginalSTDOUT);
lua_pushlightuserdata(L, OriginalHandles.StandardError);
lua_rawseti(L, RootTableStackIdx, RE_OriginalSTDERR);
/* This next step will either fetch the handle to our default console and input buffer, or create some if we don't have
any, and then restore our standard handles (which would have been overwritten had we in fact created a new console).
This step produces the same results no matter the case of whether we had a console or not. It must also be noted that
this occurs as soon as the library is loaded; there is no manual initialization (unless you want to definitely create a
new console. */
AllocConsole(); /* Fails if the process is already attached to one. */
AttachConsole(GetCurrentProcessId());
lwci_MakeScreenBufMetaTable(L); /* Must call this once before creating any ScreenBufObjs. */
lwci_MakeCoordMetaTable(L);
lwci_DoRunTimeLinking(L); /* Placed here essentially randomly. It can really go anywhere. */
lua_pushlightuserdata(L, CreateFileW(
L"CONIN$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL));
lua_rawseti(L, RootTableStackIdx, RE_CurrentInputBuf);
lwcu_PushScreenBufObjWithinLuaOpen(L, CreateFileW(
L"CONOUT$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL));
lua_pushvalue(L, -1);
lua_rawseti(L, RootTableStackIdx, RE_DefaultScreenBuf);
{CONSOLE_SCREEN_BUFFER_INFO ThisInfo;
GetConsoleScreenBufferInfo(
((ScreenBufObj*)lua_touserdata(L, -1))->Handle,
&ThisInfo);
lwcu_PushAttrib(L, ThisInfo.wAttributes);
lua_rawseti(L, RootTableStackIdx, RE_DefaultAttrib);
};
/* Here we'll take care of any color-related stuff in our initialization. */
/* It bears some explanation as to what we're doing with color-related stuff in this library, as it's the one thing where
the code is not a relatively simply mapping to the appropriate Win32 functions.
Vista allows you to get and set the "Color Table" for screenbuffers, at the same time as many of their other attributes,
such as buffer size, window position, cursor visibility, etc. etc. However, this gives the false impression that screen
buffers carry their own private color tables just as they carry their own private sizes, text data, and cursor positions, etc.
The reality is more complex, and not documented. From my experiments and observations on a 64-bit Vista Ultimate platform,
it would appear to be the case that there is only one global color table used for current rendering. When one "sets" the color
table for a buffer handle associated with the current console, the change in rendered colors will take place instantly if the
handle used is the same as the current active handle. However, if the handle used is different, then the change will take place
the next time the active screen buffer is changed, regardless of which buffer it is changed to.
So, to get the desired behavior, where every buffer appears to carry its own private color table, we have a weak table acceessible
from our library's internal functions, which has buffer objects as keys and color tables as values. Every buffer object made is
recorded in there, and upon creation, it will be given the "Default Color Table", which is initialized with the color table of the
default initial screenbuffer when the library is loaded or LuaWinCon.NewConsole() is called (this value can be changed with a call
to the new function LuaWinCon.SetDefaultColorTable().)
Whenever a call is made to the :MakeActive() method of a screenbuffer, a matching call is made to SetConsoleScreenBufferInfoEx()
using the color table found in our lookup table, using the soon-to-be-active buffer object as a key, and then the screenbuffer
is made active.
In this way, the users get the expected behavior, where they can call :SetColorTable() on any screenbuffer, with any color table,
and the console window will switch to that color scheme whenever that buffer is made active. */
if (ColorFuncsAreAvailable) {
CONSOLE_SCREEN_BUFFER_INFOEX ThisInfo;
ThisInfo.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
GetConsoleScreenBufferInfoEx(
((ScreenBufObj*)lua_touserdata(L, -1))->Handle,
&ThisInfo);
lwcu_PushColorArray(L, ThisInfo.ColorTable);
lua_rawseti(L, RootTableStackIdx, RE_DefaultColorTbl);
lua_newtable(L); /* The ColorTblLookup table. */
lua_newtable(L); /* The metatable for the above table. */
lua_pushliteral(L, "k");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2);
/* Now to place the default screenbuffer into the lookup table. */
lua_pushvalue(L, -2); /* This is the Default ScreenBuffer userdatum. */
lua_rawgeti(L, RootTableStackIdx, RE_DefaultColorTbl);
lua_settable(L, -3); /* This puts the default color table into the lookup table, with the screenbuffer as a key, and leaves the
color table on top of the stack. */
lua_rawseti(L, RootTableStackIdx, RE_ColorTblLookup);
};
lua_pop(L, 1);
/* Now to restore the standard streams... */
SetStdHandle(STD_INPUT_HANDLE, OriginalHandles.StandardInput);
SetStdHandle(STD_OUTPUT_HANDLE, OriginalHandles.StandardOutput);
SetStdHandle(STD_ERROR_HANDLE, OriginalHandles.StandardError);
/* And now, let's make our export table, then return that. */
lua_newtable(L);
lwcu_Register(L, ExportedFuncs);
return 1;
};
static lwc_Reg ExportedFuncs[] = {
#define Reg_Entry( type, func ) {type, lwcl_##func, #func}
Reg_Entry(RT_CFUNC, NewConsole),
Reg_Entry(RT_CFUNC, DefaultBuffer),
Reg_Entry(RT_CFUNC, GetNewBuffer),
Reg_Entry(RT_CFUNC, SetTitle),
Reg_Entry(RT_CFUNC, LowLevelMode),
Reg_Entry(RT_CFUNC, MakeCoord),
Reg_Entry(RT_CFUNC, SetDefaultColorTable),
Reg_Entry(RT_CFUNC, GetDefaultAttrib),
Reg_Entry(RT_CFUNC, ClearInput),
Reg_Entry(RT_CFUNC, IsInputAvailable),
Reg_Entry(RT_CFUNC, FetchInput),
{RT_SENTRY, NULL}
#undef Reg_Entry
};
static void lwci_MakeScreenBufMetaTable(lua_State *L) {
lwci_MakeScreenBufMethodTable(L);
lua_createtable(L, 0, 2);
lua_rawgeti(L, RootTableStackIdx, RE_ScreenBufMethodTable);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lwcsbm_gc);
lua_setfield(L, -2, "__gc");
lua_rawseti(L, RootTableStackIdx, RE_ScreenBufMetaTable);
return;
};
static void lwci_MakeScreenBufMethodTable(lua_State *L) { /* Saves the Screenbuffer method table into its appropriate upvalue. */
lua_newtable(L);
lwcu_Register(L, ScreenBufMethods);
lua_rawseti(L, RootTableStackIdx, RE_ScreenBufMethodTable);
return;
};
static lwc_Reg ScreenBufMethods[] = {
#define Reg_Entry( type, func ) {type, lwcsbm_##func, #func}
Reg_Entry(RT_CFUNC, Close),
Reg_Entry(RT_CFUNC, MakeActive),
Reg_Entry(RT_CFUNC, GetLargestWindowSize),
Reg_Entry(RT_CFUNC, SetCursorVisible),
Reg_Entry(RT_CFUNC, SetCursorPosition),
Reg_Entry(RT_CFUNC, SetCursorSize),
Reg_Entry(RT_CFUNC, SetScreenBufferSize),
Reg_Entry(RT_CFUNC, SetWindowPositionAndSize),
Reg_Entry(RT_CFUNC, FillRegion),
Reg_Entry(RT_CFUNC, WriteRegion),
Reg_Entry(RT_CFUNC, WriteRun),
Reg_Entry(RT_CFUNC, SetColorTable),
#if 0
Reg_Entry(RT_CFUNC, GetColorTable),
#endif
{RT_SENTRY, NULL}
#undef Reg_Entry
};
static void lwci_MakeCoordMetaTable(lua_State *L) {
luaL_loadstring(L, coord_MakeMetaTableString);
lua_call(L, 0, 1);
lua_rawseti(L, RootTableStackIdx, RE_CoordMetaTable);
return;
};
static void lwci_PushUpvalues(lua_State *L) {
lua_pushvalue(L, RootTableStackIdx);
luaL_loadstring(L, vk_MakeTableFuncString);
lua_call(L, 0, 1);
return;
};
static void lwci_DoRunTimeLinking(lua_State *L) {
HMODULE hK32 = GetModuleHandleW(L"kernel32.dll");
GetConsoleScreenBufferInfoEx = (PGCSBIEx)GetProcAddress(
hK32,
"GetConsoleScreenBufferInfoEx"
);
SetConsoleScreenBufferInfoEx = (PSCSBIEx)GetProcAddress(
hK32,
"SetConsoleScreenBufferInfoEx"
);
return;
};
/* SEC_LIB */
/* * * * * * * * * * * * * * * *
SECTION CONTENTS
Uncategorized . . . . . SECSUB_LIB@UNCAT
Input Functions . . . . SECSUB_LIB@INPUT
* * * * * * * * * * * * * * * */
/* SECSUB_LIB_UNCAT SECSUB_LIB@UNCAT */
static int lwcl_NewConsole(lua_State *L) { /* TODO: Come back and finish this. */
/* Get us our new console. */
FreeConsole();
AllocConsole();
AttachConsole(GetCurrentProcessId());
/* Now restore things to their proper place. */
lua_rawgeti(L, UPV_RootTable, RE_OriginalSTDIN);
lua_rawgeti(L, UPV_RootTable, RE_OriginalSTDOUT);
lua_rawgeti(L, UPV_RootTable, RE_OriginalSTDERR);
SetStdHandle(STD_INPUT_HANDLE, (HANDLE)lua_touserdata(L, -3));
SetStdHandle(STD_OUTPUT_HANDLE, (HANDLE)lua_touserdata(L, -2));
SetStdHandle(STD_ERROR_HANDLE, (HANDLE)lua_touserdata(L, -1));
lua_pop(L, 3);
lua_pushlightuserdata(L, CreateFileW(
L"CONIN$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL));
FlushConsoleInputBuffer((HANDLE)lua_touserdata(L, -1));
lua_rawseti(L, UPV_RootTable, RE_CurrentInputBuf);
lwcu_PushScreenBufObj(L, CreateFileW(
L"CONOUT$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL));
SetConsoleActiveScreenBuffer(((ScreenBufObj*)lua_touserdata(L, -1))->Handle);
{CONSOLE_SCREEN_BUFFER_INFO ThisInfo;
GetConsoleScreenBufferInfo(
((ScreenBufObj*)lua_touserdata(L, -1))->Handle,
&ThisInfo);
lwcu_PushAttrib(L, ThisInfo.wAttributes);
lua_rawseti(L, UPV_RootTable, RE_DefaultAttrib);
};
if (ColorFuncsAreAvailable) {
CONSOLE_SCREEN_BUFFER_INFOEX ThisInfo;
ThisInfo.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
lua_rawgeti(L, UPV_RootTable, RE_ColorTblLookup);
lua_pushvalue(L, -2); /* The screenbuffer. */
GetConsoleScreenBufferInfoEx(
((ScreenBufObj*)lua_touserdata(L, -1))->Handle,
&ThisInfo);
lwcu_PushColorArray(L, ThisInfo.ColorTable);
lua_pushvalue(L, -1);
lua_rawseti(L, UPV_RootTable, RE_DefaultColorTbl);
/* At the moment, the top of the stack contains the color table, below that is the screenbuffer, below that is the ColorTblLookup.*/
lua_settable(L, -3);
lua_pop(L, 1); /* Now the stack is as it was before this optional section was entered into. */
};
lua_rawseti(L, UPV_RootTable, RE_DefaultScreenBuf);
/* Well, I don't really have a good way to detect errors at the moment (not that it'd be hard to think of one), so I'll just
blithely return true here for no good reason. */
lua_pushboolean(L, TRUE);
return 1;
};
static int lwcl_DefaultBuffer(lua_State *L) {
int numargs = lua_gettop(L);
if (numargs > 1) {
return luaL_error(L, "Invalid number of arguments to function 'DefaultBuffer', please pass exactly 0 or 1 arguments!");
} else if (numargs == 1) {
if (!lwcu_IsAScreenBuffer(L, 1)) {
return luaL_error(L, NotAScreenBufferErrString, 1, "DefaultBuffer");
};
lua_rawseti(L, UPV_RootTable, RE_DefaultScreenBuf);
lua_pushboolean(L, TRUE);
return 1;
} else { /* if (numargs == 0) */
lua_rawgeti(L, UPV_RootTable, RE_DefaultScreenBuf);
return 1;
};
};
static int lwcl_GetNewBuffer(lua_State *L) {
HANDLE ThisHandle;
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "GetNewBuffer", 0);
};
ThisHandle = CreateConsoleScreenBuffer(
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
CONSOLE_TEXTMODE_BUFFER,
NULL);
if (ThisHandle == INVALID_HANDLE_VALUE) {
lua_pushnil(L);
return 1;
};
lwcu_PushScreenBufObj(L, ThisHandle);
if (ColorFuncsAreAvailable) {
CONSOLE_SCREEN_BUFFER_INFOEX ThisInfo;
int orig_idx = lua_gettop(L);
ThisInfo.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
lua_rawgeti(L, UPV_RootTable, RE_DefaultColorTbl);
lua_rawgeti(L, UPV_RootTable, RE_ColorTblLookup);
lua_pushvalue(L, -3); /* The buffer. */
lua_pushvalue(L, -3); /* The default color table. */
lua_settable(L, -3);
#if 0
lua_pop(L, 1); /* Pop the lookup table. */
/* The default color table is on top. */
GetConsoleScreenBufferInfoEx(ThisHandle, &ThisInfo);
ThisInfo.srWindow.Right += 1;
ThisInfo.srWindow.Bottom += 1;
lwcu_ToColorArray(L, -1, ThisInfo.ColorTable);
lua_pop(L, 1);
SetConsoleScreenBufferInfoEx(ThisHandle, &ThisInfo);
#endif
lua_settop(L, orig_idx);
};
return 1;
};
static int lwcl_SetTitle(lua_State *L) {
/* Designer's Note:
It was considered making this function respect __tostring metamethods.
However, it was determined that making other functions similarly respect
__tostring in places where strings would be expected, would be far too
difficult to implement properly, if even possible at all.
Ultimately, the decision was that sacrificing some ease-of-use here,
for an admittedly-uncommon situation, was worth keeping useage consistent
throughout the implementation. Principle of Least Surprise. */
LPCWSTR ThisTitleString;
if (lua_gettop(L) != 1) {
return luaL_error(L, NumArgsErrString, "SetTitle", 1);
} else if (!(lua_isstring(L, 1))) {
return luaL_error(L, NotAStringOrConvertibleErrString, 1, "SetTitle");
};
lua_pushliteral(L, "\x00");
lua_concat(L, 2); /* Have to ensure it's nul-terminated. */
ThisTitleString = luaW_tostring(L, 1);
lua_pushboolean(L, SetConsoleTitleW(ThisTitleString));
return 1;
};
/* IMPLEMENTATION-SPECIFIC FUNCTION */
static int lwcl_LowLevelMode(lua_State *L) {
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "LowLevelMode", 0);
};
lua_rawgeti(L, UPV_RootTable, RE_CurrentInputBuf);
lua_pushboolean(L, SetConsoleMode(
(HANDLE)lua_touserdata(L, -1),
ENABLE_EXTENDED_FLAGS | ENABLE_MOUSE_INPUT)
);
return 1;
};
/* IMPLEMENTATION-SPECIFIC FUNCTION */
static int lwcl_MakeCoord(lua_State *L) {
COORD ThisCord;
if (lua_gettop(L) == 1) {
if (lwcu_IsACoord(L, 1)) {
lua_pushinteger(L, 1);
lua_gettable(L, -2);
lua_pushinteger(L, 2);
lua_gettable(L, -3);
ThisCord.X = lua_tointeger(L, -2);
ThisCord.Y = lua_tointeger(L, -1);
} else {
return luaL_error(L, "Invalid argument #1 to function 'MakeCoord': not a coord! (MakeCoord takes a coord or two numbers)");
};
} else if (lua_gettop(L) == 2) {
if (lua_isnumber(L, 1) && lua_isnumber(L, 2)) {
ThisCord.X = lua_tointeger(L, 1);
ThisCord.Y = lua_tointeger(L, 2);
} else {
return luaL_error(L, "Invalid arguments #1 and/or #2 to function 'MakeCoord': not both numbers! (MakeCoord takes a coord or two numbers)");
};
} else {
return luaL_error(L, NumArgsRangeErrString, "MakeCoord", 1, 2);
};
lwcu_PushCoord(L, ThisCord, 0);
return 1;
};
static int lwcl_SetDefaultColorTable(lua_State *L) {
if (lua_gettop(L) != 1) {
return luaL_error(L, NumArgsErrString, "SetDefaultColorTable", 1);
};
if (!lwcu_IsAColorArray(L, 1)) {
return luaL_error(L, NotAColorArrayErrString, 1, "SetDefaultColorTable");
};
if (!(ColorFuncsAreAvailable)) {
lua_pushnil(L);
return 1;
};
lua_rawseti(L, UPV_RootTable, RE_DefaultColorTbl);
lua_pushboolean(L, TRUE);
return 1;
};
static int lwcl_GetDefaultAttrib(lua_State *L) {
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "GetDefaultAttrib", 0);
};
lua_rawgeti(L, UPV_RootTable, RE_DefaultAttrib);
return 1;
};
/* SECSUB_LIB_INPUT SECSUB_LIB@INPUT */
static int lwcl_ClearInput(lua_State *L) {
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "ClearInput", 0);
};
lua_rawgeti(L, UPV_RootTable, RE_CurrentInputBuf);
lua_pushboolean(L, FlushConsoleInputBuffer((HANDLE)lua_touserdata(L, -1)));
return 1;
};
static int lwcl_IsInputAvailable(lua_State *L) {
INPUT_RECORD ThisInputRecord;
DWORD NumberOfRecords;
HANDLE ThisHandle;
lua_rawgeti(L, UPV_RootTable, RE_CurrentInputBuf);
ThisHandle = lua_touserdata(L, -1);
lua_pop(L, 1);
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "IsInputAvailable", 0);
};
/* The point here is to repeatedly Peek input records until we run out, or we discover
one which is a KEYBOARD_RECORD or MOUSE_RECORD. We will also discard any input records
which do not match. */
GetNumberOfConsoleInputEvents(
ThisHandle,
&NumberOfRecords);
if (NumberOfRecords == 0) {
lua_pushboolean(L, FALSE);
return 1;
};
while (TRUE) {
BOOL Result = PeekConsoleInputW(
ThisHandle,
&ThisInputRecord,
1,
&NumberOfRecords);
if (!Result) {
lua_pushnil(L);
break;
};
if (NumberOfRecords == 0) {
lua_pushboolean(L, FALSE);
break;
};
if ((ThisInputRecord.EventType == KEY_EVENT) ||
(ThisInputRecord.EventType == MOUSE_EVENT)) {
lua_pushboolean(L, TRUE);
break;
} else {
/* The results from this will simply be discarded. */
ReadConsoleInputW(
ThisHandle,
&ThisInputRecord,
1,
&NumberOfRecords);
};
};
return 1;
};
static int lwcl_FetchInput(lua_State *L) {
INPUT_RECORD ThisInputRecord;
HANDLE ThisHandle;
DWORD dummy;
lua_rawgeti(L, UPV_RootTable, RE_CurrentInputBuf);
ThisHandle = (HANDLE)lua_touserdata(L, -1);
lua_pop(L, 1);
if (lua_gettop(L) != 0) {
return luaL_error(L, NumArgsErrString, "FetchInput", 0);
};
while (TRUE) {
BOOL Result = ReadConsoleInputW(
ThisHandle,
&ThisInputRecord,
1,
&dummy);
if (!Result) {
lua_pushnil(L);
return 1;
};
if ((ThisInputRecord.EventType == KEY_EVENT) ||
(ThisInputRecord.EventType == MOUSE_EVENT)) {
break;
};
};
switch (ThisInputRecord.EventType) {
case KEY_EVENT :
lua_pushliteral(L, "key");
lwcu_PushKeyRecord(L, &ThisInputRecord.Event.KeyEvent);
break;
case MOUSE_EVENT :
lua_pushliteral(L, "mouse");
lwcu_PushMouseRecord(L, &ThisInputRecord.Event.MouseEvent);
break;
};
return 2;
};
/* SEC_UTIL */
/* * * * * * * * * * * * * * * *
SECTION CONTENTS
Uncategorized . . . . . SECSUB_UTIL@UNCAT
Coord Functions . . . . SECSUB_UTIL@CORD
Attrib Functions. . . . SECSUB_UTIL@ATTR
ScreenBuffer Functions SECSUB_UTIL@SCRB
Input Record Functions SECSUB_UTIL@INRC
Color Array Functions . SECSUB_UTIL@COLARR
* * * * * * * * * * * * * * * */
/* SECSUB_UTIL_UNCAT SECSUB_UTIL@UNCAT */
static void lwcu_Register(lua_State *L, lwc_Reg list[]) {
/* This is essentially an equivalent to luaL_setfuncs() and luaL_register() but better-suited to our
particular needs.
It registers all of the functions given in list[] into the table at the top of the stack. list[]
must end in an entry whose .Type is RT_SENTRY. */
{int i;
for (i = 0; list[i].Type != RT_SENTRY; i++) {
switch (list[i].Type) {
case RT_CFUNC :
lwci_PushUpvalues(L);
lua_pushcclosure(L, list[i].F.CFunc, NumberOfUpvalues);
lua_setfield(L, -2, list[i].Name);
break;
case RT_LFUNC :
luaL_loadstring(L, list[i].F.LFunc);
lua_call(L, 0, 1);
lua_setfield(L, -2, list[i].Name);
break;
};
};};
return;
};
/* This is a separate Lua function used by several other functions here. It takes one argument, any value,
and returns nothing. It exists solely to be lua_pcall'd. All it does is attempt to perform arg1[1] and arg1[2],
in an attempt to trigger "value cannot be indexed" errors. */
static int lwcu_AttemptToIndex(lua_State *L) {
if (lua_gettop(L) != 1) { /* Should always have specifically 1 argument, if not, we have a coding error. */
lua_pushnil(L);
return lua_error(L);
};
lua_pushinteger(L, 1);
lua_gettable(L, 1); /* Index val[1] */
lua_pushinteger(L, 2);
lua_gettable(L, 1); /* Index val[2] */
return 0;
};
/* SECSUB_UTIL_CORD SECSUB_UTIL@CORD */
static int lwcu_IsACoord(lua_State *L, int idx) {
/* Designer's Notes:
The library specification says that a coord's Value[1] and Value[2] must be "integer numbers,
or convertible to integer numbers as per the usual Lua rules". This implementation chooses to interpret
this to mean that a non-integer number, passed through the lua_tointeger() and "truncated in some
non-specified way", counts as "convertible to [an] integer".
Therefore, merely being a number, or a string convertible to a number, is sufficient to qualify
as a valid value of a coord, however it cannot be guaranteed that the actual values will be used.*/
lua_pushcfunction(L, lwcu_AttemptToIndex);
lua_pushvalue(L, idx);
if (lua_pcall(L, 1, 0, 0) != 0) {
return 0;
};
lua_pushinteger(L, 1);
lua_gettable(L, idx); /* lua_gettable(), not lua_rawgeti(). LuaWinCon respects metamethods in this. */
lua_pushinteger(L, 2);
lua_gettable(L, idx);
if (lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
lua_pop(L, 2);
return 1;
} else {
lua_pop(L, 2);
return 0;
};
};
static int lwcu_IsAPositionCoord(lua_State *L, int idx) {
/* THIS FUNCTION ASSUMES THAT THE VALUE IS ALREADY KNOWN TO BE A VALID COORD.
BE SURE TO RUN THE VALUE THROUGH lwcu_IsACoord() FIRST BEFORE PASSING IT THROUGH
THIS FUNCTION. */
lua_pushinteger(L, 1);
lua_gettable(L, idx);
lua_pushinteger(L, 2);
lua_gettable(L, idx);
if ((lua_tointeger(L, -2) > 0) && (lua_tointeger(L, -1) > 0)) {
lua_pop(L, 2);
return 1;
} else {
lua_pop(L, 2);
return 0;
};
};
static int lwcu_IsASizeCoord(lua_State *L, int idx) {
/* THIS FUNCTION ASSUMES THAT THE VALUE IS ALREADY KNOWN TO BE A VALID COORD.
BE SURE TO RUN THE VALUE THROUGH lwcu_IsACoord() FIRST BEFORE PASSING IT THROUGH
THIS FUNCTION. */
lua_pushinteger(L, 1);
lua_gettable(L, idx);
lua_pushinteger(L, 2);
lua_gettable(L, idx);
if ((lua_tointeger(L, -2) >= 0) && (lua_tointeger(L, -1) >= 0)) {
lua_pop(L, 2);
return 1;
} else {
lua_pop(L, 2);
return 0;
};
};
static void lwcu_PushCoord(lua_State *L, COORD C, signed int Adjustment) {
/* Pushes a 'coord' onto the stack with the appropriate metatable and everything. Its values
correspond to the values of 'C', adjusted by the value of 'Adjustment'. */
lua_createtable(L, 2, 0);
lua_pushinteger(L, C.X + Adjustment);
lua_rawseti(L, -2, 1);
lua_pushinteger(L, C.Y + Adjustment);
lua_rawseti(L, -2, 2);
lua_rawgeti(L, UPV_RootTable, RE_CoordMetaTable);
lua_setmetatable(L, -2);
return;
};
static COORD lwcu_ToCoord(lua_State *L, int idx, signed int Adjustment) {
/* THIS FUNCTION ASSUMES THAT THE VALUE AT 'idx' IS ALREADY KNOWN TO BE A VALID COORD.
BE SURE TO RUN THE VALUE THROUGH lwcu_IsACoord() FIRST BEFORE PASSING IT THROUGH THIS
FUNCTION.
Takes the coord at stack index 'idx' and converts it into a COORD, applying the
value 'Adjustment' to the interior values of the COORD. */
COORD RetCoord;
lua_pushinteger(L, 1);
lua_gettable(L, idx);
RetCoord.X = (SHORT)(lua_tointeger(L, -1) + Adjustment);
lua_pushinteger(L, 2);
lua_gettable(L, idx);
RetCoord.Y = (SHORT)(lua_tointeger(L, -1) + Adjustment);
return RetCoord;
};
/* SECSUB_UTIL_ATTR SECSUB_UTIL@ATTR */
static int lwcu_IsAnAttrib(lua_State *L, int idx) {
/* Designer's notes:
According to specifications, an implementation is absolutely free to define the structure
of an 'attrib', or even to choose not to define it all and instead provide some opaque values
to use as attribs.
Our implementation, as usual, reflects the way the actual Win32 Console works. However, the
actual way it works is not the same way that most programs usually interact with it, at a low
level.
Usually, one builds up a color by using a mixture of bitwise flags called:
FOREGROUND_BLUE BACKGROUND_BLUE
FOREGROUND_GREEN BACKGROUND_GREEN
FOREGROUND_RED BACKGROUND_RED
FOREGROUND_INTENSITY BACKGROUND_INTENSITY
(along with some additional flags used only for Far-East languages)
And thus, one might expect that we would define an 'attrib' as an array of two strings used
as enumeration values for predefined colors like "Red", "Bright Red", "Cyan", etc.
However, in reality, those bitwise flags build up a 4-bit index into a screenbuffer's
"Color Table", which actually contains 24-bit RGB values. So, we have defined an attrib as being
any value for which value[1] and value[2] produce integers (or values convertible to integers as
per usual Lua rules) in the range 1..16. value[1] indicates the foreground color, and value[2]
indicates the background color.
As with coords, this function will perform the usual Lua truncation of non-integer numbers. */
lua_pushcfunction(L, lwcu_AttemptToIndex);
lua_pushvalue(L, idx);
if (lua_pcall(L, 1, 0, 0) != 0) {
return 0;
};
lua_pushinteger(L, 1);
lua_gettable(L, idx);
lua_pushinteger(L, 2);
lua_gettable(L, idx);
if (!(lua_isnumber(L, -2) && lua_isnumber(L, -1))) {
lua_pop(L, 2);
return 0;
} else {
lua_Integer Candidate1 = lua_tointeger(L, -2);
lua_Integer Candidate2 = lua_tointeger(L, -1);
if (!(((Candidate1 >= 1) && (Candidate1 <= 16)) && ((Candidate2 >= 1) && Candidate2 <= 16))) {
lua_pop(L, 2);
return 0;
} else {
lua_pop(L, 2);
return 1;
};
};
};
static WORD lwcu_ToAttrib(lua_State *L, int idx) {
/* This function assumes the value has already been checked for validity! Do not run this
function without first running lwcu_IsAnAttrib() on the value! */
WORD ThisAttrib = 0;
lua_pushinteger(L, 1);
lua_gettable(L, idx);
ThisAttrib = (((WORD)lua_tointeger(L, -1) - 1) & 0x0F);
lua_pushinteger(L, 2);
lua_gettable(L, idx);
ThisAttrib |= ((((WORD)lua_tointeger(L, -1) - 1) & 0x0F) << 4);
lua_pop(L, 2);
return ThisAttrib;
};
static void lwcu_PushAttrib(lua_State *L, WORD attr) {
lua_createtable(L, 2, 0);
lua_pushinteger(L, (attr & 0x0F)+1);
lua_rawseti(L, -2, 1);
lua_pushinteger(L, ((attr & 0xF0) >> 4)+1);
lua_rawseti(L, -2, 2);
return;
};
/* SECSUB_UTIL_SCRB SECSUB_UTIL@SCRB */
static int lwcu_IsAScreenBuffer(lua_State *L, int idx) {
if (!(lua_isuserdata(L, idx))) {
return 0;
} else if (!(lua_getmetatable(L, idx))) {/* This pushes the metatable onto the stack if it succeeds. */
return 0;
} else {
lua_rawgeti(L, UPV_RootTable, RE_ScreenBufMetaTable);
if (!lua_equal(L, -2, -1)) {
lua_pop(L, 2);
return 0;
} else {
lua_pop(L, 2);
return 1;
};
};
};
static void lwcu_PushScreenBufObjWithinLuaOpen(lua_State *L, HANDLE ThisHandle) {
/* This is just like the normal version of lwcu_PushScreenBufObj except it's designed to work
within the luaopen_LuaWinCon function, where we cannot access the shared RootTable as an upvalue. */
ScreenBufObj* ThisBufObj = (ScreenBufObj*)lua_newuserdata(L, sizeof(ScreenBufObj));
ThisBufObj->Handle = ThisHandle;
lua_rawgeti(L, RootTableStackIdx, RE_ScreenBufMetaTable);
lua_setmetatable(L, -2);
return;
};
static void lwcu_PushScreenBufObj(lua_State *L, HANDLE ThisHandle) {
ScreenBufObj* ThisBufObj = (ScreenBufObj*)lua_newuserdata(L, sizeof(ScreenBufObj));
ThisBufObj->Handle = ThisHandle;
lua_rawgeti(L, UPV_RootTable, RE_ScreenBufMetaTable);
lua_setmetatable(L, -2);
return;
};
/* SECSUB_UTIL_INRC SECSUB_UTIL@INRC */
#define PushControlKeyState(L, Keys) \
lua_pushboolean(L, Keys & CAPSLOCK_ON); \
lua_setfield(L, -2, "CapsLockIsOn"); \
lua_pushboolean(L, Keys & NUMLOCK_ON); \
lua_setfield(L, -2, "NumLockIsOn"); \
lua_pushboolean(L, Keys & SCROLLLOCK_ON); \
lua_setfield(L, -2, "ScrollLockIsOn"); \
lua_pushboolean(L, Keys & SHIFT_PRESSED); \
lua_setfield(L, -2, "ShiftIsDown"); \
lua_pushboolean(L, Keys & LEFT_ALT_PRESSED); \
lua_setfield(L, -2, "LeftAltIsDown"); \
lua_pushboolean(L, Keys & LEFT_CTRL_PRESSED); \
lua_setfield(L, -2, "LeftCtrlIsDown"); \
lua_pushboolean(L, Keys & RIGHT_ALT_PRESSED); \
lua_pushvalue(L, -1); \
lua_setfield(L, -3, "RightAltIsDown"); \
lua_setfield(L, -2, "AltGrIsDown"); \
lua_pushboolean(L, Keys & RIGHT_CTRL_PRESSED); \
lua_setfield(L, -2, "RightCtrlIsDown")
static void lwcu_PushKeyRecord(lua_State *L, KEY_EVENT_RECORD *K) {
lua_newtable(L);
lua_pushboolean(L, K->bKeyDown);
lua_setfield(L, -2, "IsDown");
lua_pushinteger(L, (lua_Integer)K->wRepeatCount);
lua_setfield(L, -2, "RepeatCount");
lua_pushinteger(L, (lua_Integer)K->wVirtualKeyCode);
lua_pushvalue(L, -1);
lua_setfield(L, -3, "KeyCode");
lua_rawget(L, UPV_KeyCodeTranslationTable);
lua_setfield(L, -2, "Key");
lua_pushinteger(L, (lua_Integer)K->wVirtualScanCode);
lua_setfield(L, -2, "ScanCode");
luaW_pushlstring(L, &K->uChar.UnicodeChar, (K->uChar.UnicodeChar == 0x0000) ? 0 : 1);
lua_setfield(L, -2, "Character");
{DWORD ControlKeys = K->dwControlKeyState;
lua_pushboolean(L, ControlKeys & ENHANCED_KEY);
lua_setfield(L, -2, "IsEnhancedKey");
PushControlKeyState(L, ControlKeys);
};
return;
};
static void lwcu_PushMouseRecord(lua_State *L, MOUSE_EVENT_RECORD *M) {
lua_newtable(L);
/* Push mouse position. */
lwcu_PushCoord(L, M->dwMousePosition, 1);
lua_setfield(L, -2, "Position");
/* Push mouse button table. */
/* We used to make this in a loop, but we might as well do it manually now. */
lua_createtable(L, 5, 2);
{DWORD ButtonState = M->dwButtonState;
lua_pushboolean(L, ButtonState & FROM_LEFT_1ST_BUTTON_PRESSED);
lua_pushvalue(L, -1);
lua_rawseti(L, -3, 1);
lua_setfield(L, -2, "left");
lua_pushboolean(L, ButtonState & RIGHTMOST_BUTTON_PRESSED);
lua_pushvalue(L, -1);
lua_rawseti(L, -3, 2);
lua_setfield(L, -2, "right");