-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathwinapi.l.c
2164 lines (1944 loc) · 57.3 KB
/
winapi.l.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
/***
A useful set of Windows API functions.
* Enumerating and accessing windows, including sending keys.
* Enumerating processes and querying their program name, memory used, etc.
* Reading and Writing to the Registry
* Copying and moving files, and showing drive information.
* Launching processes and opening documents.
* Monitoring filesystem changes.
@author Steve Donovan ([email protected])
@copyright 2011
@license MIT/X11
@module winapi
*/
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#include <string.h>
#ifdef __GNUC__
#include <winable.h> /* GNU GCC specific */
#endif
#include "Winnetwk.h"
#include <psapi.h>
#define WBUFF 2048
#define MAX_SHOW 100
#define THREAD_STACK_SIZE (1024 * 1024)
#define MAX_PROCESSES 1024
#define MAX_KEYS 512
#define FILE_BUFF_SIZE 2048
#define MAX_WATCH 20
#define MAX_WPATH 1024
#define TIMEOUT(timeout) timeout == 0 ? INFINITE : timeout
static wchar_t wbuff[WBUFF];
typedef LPCWSTR WStr;
module "winapi" {
#include "wutils.h"
static WStr wstring(Str text) {
return wstring_buff(text,wbuff,sizeof(wbuff));
}
/// Text encoding.
// @section encoding
/// set the current text encoding.
// @param e one of `CP_ACP` (Windows code page; default) and `CP_UTF8`
// @function set_encoding
def set_encoding (Int e) {
set_encoding(e);
return 0;
}
/// get the current text encoding.
// @return either `CP_ACP` or `CP_UTF8`
// @function get_encoding
def get_encoding () {
lua_pushinteger(L, get_encoding());
return 1;
}
/// encode a string in another encoding.
// Note: currently there's a limit of about 2K on the string buffer.
// @param e_in `CP_ACP`, `CP_UTF8` or `CP_UTF16`
// @param e_out likewise
// @param text the string
// @function encode
def encode(Int e_in, Int e_out, Str text) {
int ce = get_encoding();
LPCWSTR ws;
if (e_in != -1) {
set_encoding(e_in);
ws = wstring(text);
} else {
ws = (LPCWSTR)text;
}
if (e_out != -1) {
set_encoding(e_out);
push_wstring(L,ws);
} else {
lua_pushlstring(L,(LPCSTR)ws,wcslen(ws)*sizeof(WCHAR));
}
set_encoding(ce);
return 1;
}
/// expand # unicode escapes in a string.
// @param text ASCII text with #XXXX, where XXXX is four hex digits. ## means # itself.
// @return text as UTF-8
// @see testu.lua
// @function utf8_expand
def utf8_expand(Str text) {
int len = strlen(text), i = 0, enc = get_encoding();
WCHAR wch;
LPWSTR P = wbuff;
if (len > sizeof(wbuff)) {
return push_error_msg(L,"string too big");
}
while (i <= len) {
if (text[i] == '#') {
++i;
if (text[i] == '#') {
wch = '#';
} else
if (len-i >= 4) {
char hexnum[5];
strncpy(hexnum,text+i,4);
hexnum[4] = '\0';
wch = strtol(hexnum,NULL,16);
i += 3;
} else {
return push_error_msg(L,"bad # escape");
}
} else {
wch = (WCHAR)text[i];
}
*P++ = wch;
++i;
}
*P++ = 0;
set_encoding(CP_UTF8);
push_wstring(L,wbuff);
set_encoding(enc);
return 1;
}
// forward reference to Process constructor
static int push_new_Process(lua_State *L,Int pid, HANDLE ph);
const DWORD_PTR WIN_NOACTIVATE = (DWORD_PTR)SWP_NOACTIVATE,
WIN_NOMOVE = (DWORD_PTR)SWP_NOMOVE,
WIN_NOSIZE = (DWORD_PTR)SWP_NOSIZE,
WIN_SHOWWINDOW = (DWORD_PTR)SWP_SHOWWINDOW,
WIN_NOZORDER = (DWORD_PTR)SWP_NOZORDER,
WIN_BOTTOM = (DWORD_PTR)HWND_BOTTOM,
WIN_NOTOPMOST = (DWORD_PTR)HWND_NOTOPMOST,
WIN_TOP = (DWORD_PTR)HWND_TOP,
WIN_TOPMOST = (DWORD_PTR)HWND_TOPMOST;
/// a class representing a Window.
// @type Window
class Window {
HWND hwnd;
constructor (HWND h) {
this->hwnd = h;
}
static lua_State *sL;
static BOOL CALLBACK enum_callback(HWND hwnd,LPARAM data) {
push_ref(sL,(Ref)data);
push_new_Window(sL,hwnd);
lua_call(sL,1,0);
return TRUE;
}
/// the handle of this window.
// @function get_handle
def get_handle() {
lua_pushnumber(L,(DWORD_PTR)this->hwnd);
return 1;
}
/// get the window text.
// @function get_text
def get_text() {
GetWindowTextW(this->hwnd,wbuff,sizeof(wbuff));
return push_wstring(L,wbuff);
}
/// set the window text.
// @function set_text
def set_text(Str text) {
SetWindowTextW(this->hwnd,wstring(text));
return 0;
}
/// change the visibility, state etc
// @param flags one of `SW_SHOW`, `SW_MAXIMIZE`, etc
// @function show
def show(Int flags = SW_SHOW) {
ShowWindow(this->hwnd,flags);
return 0;
}
/// change the visibility without blocking.
// @param flags one of `SW_SHOW`, `SW_MAXIMIZE`, etc
// @function show_async
def show_async(Int flags = SW_SHOW) {
ShowWindowAsync(this->hwnd,flags);
return 0;
}
/// get the position in pixels
// @return left position
// @return top position
// @function get_position
def get_position() {
RECT rect;
GetWindowRect(this->hwnd,&rect);
lua_pushinteger(L,rect.left);
lua_pushinteger(L,rect.top);
return 2;
}
/// get the bounds in pixels
// @return width
// @return height
// @function get_bounds
def get_bounds() {
RECT rect;
GetWindowRect(this->hwnd,&rect);
lua_pushinteger(L,rect.right - rect.left);
lua_pushinteger(L,rect.bottom - rect.top);
return 2;
}
/// is this window visible?
// @function is_visible
def is_visible() {
lua_pushboolean(L,IsWindowVisible(this->hwnd));
return 1;
}
/// destroy this window.
// @function destroy
def destroy () {
DestroyWindow(this->hwnd);
return 0;
}
/// resize this window.
// @param x0 left
// @param y0 top
// @param w width
// @param h height
// @function resize
def resize(Int x0, Int y0, Int w, Int h) {
MoveWindow(this->hwnd,x0,y0,w,h,TRUE);
return 0;
}
/// resize or move a window.
// see [API](http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx)
// @param w window _handle_ to insert after, or one of:
// WINWIN_BOTTOM, WIN_NOTOPMOST, WIN_TOP (default), WIN_TOPMOST
// @param x0 left (ignore if flags has WIN_NOMOVE)
// @param y0 top
// @param w width (ignore if flags has WIN_NOSIZE)
// @param h height
// @param flags one of
// WIN_NOACTIVATE, WIN_NOMOVE, WIN_NOSIZE, WIN_SHOWWINDOW (default), WIN_NOZORDER
def set_pos (Int wafter = WIN_TOP, Int x0, Int y0, Int w, Int h, Int flags = WIN_SHOWWINDOW) {
SetWindowPos(this->hwnd,(HWND)(DWORD_PTR)wafter,x0,y0,w,h,flags);
return 0;
}
/// send a message.
// @param msg the message
// @param wparam
// @param lparam
// @return the result
// @function send_message
def send_message(Int msg, Number wparam, Number lparam) {
lua_pushinteger(L,SendMessage(this->hwnd,msg,(WPARAM)wparam,(LPARAM)lparam));
return 1;
}
/// send a message asynchronously.
// @param msg the message
// @param wparam
// @param lparam
// @return the result
// @function post_message
def post_message(Int msg, Number wparam, Number lparam) {
return push_bool(L,PostMessage(this->hwnd,msg,(WPARAM)wparam,(LPARAM)lparam));
}
/// enumerate all child windows.
// @param a callback which to receive each window object
// @function enum_children
def enum_children(Value callback) {
Ref ref;
sL = L;
ref = make_ref(L,callback);
EnumChildWindows(this->hwnd,&enum_callback,ref);
release_ref(L,ref);
return 0;
}
/// get the parent window.
// @function get_parent
def get_parent() {
return push_new_Window(L,GetParent(this->hwnd));
}
/// get the name of the program owning this window.
// @function get_module_filename
def get_module_filename() {
int sz = GetWindowModuleFileNameW(this->hwnd,wbuff,sizeof(wbuff));
wbuff[sz] = 0;
return push_wstring(L,wbuff);
}
/// get the window class name.
// Useful to find all instances of a running program, when you
// know the class of the top level window.
// @function get_class_name
def get_class_name() {
static char buff[1024];
int n = GetClassName(this->hwnd,buff,sizeof(buff));
if (n > 0) {
lua_pushstring(L,buff);
return 1;
} else {
return push_error(L);
}
}
/// bring this window to the foreground.
// @function set_foreground
def set_foreground () {
lua_pushboolean(L,SetForegroundWindow(this->hwnd));
return 1;
}
/// get the associated process of this window
// @function get_process
def get_process() {
DWORD pid;
GetWindowThreadProcessId(this->hwnd,&pid);
return push_new_Process(L,pid,NULL);
}
/// this window as string (up to 100 chars).
// @function __tostring
def __tostring() {
int ret;
int sz = GetWindowTextW(this->hwnd,wbuff,sizeof(wbuff));
if (sz > MAX_SHOW) {
wbuff[MAX_SHOW] = '\0';
}
ret = push_wstring(L,wbuff);
if (ret == 2) { // we had a conversion error
lua_pushliteral(L,"");
}
return 1;
}
def __eq(Window other) {
lua_pushboolean(L,this->hwnd == other->hwnd);
return 1;
}
}
/// Manipulating Windows.
// @section Windows
/// find a window based on classname and caption
// @param cname class name (may be nil)
// @param wname caption (may be nil)
// @return @{Window}
// @function find_window
def find_window(StrNil cname, StrNil wname) {
HWND hwnd = FindWindow(cname,wname);
if (hwnd == NULL) {
return push_error(L);
} else {
return push_new_Window(L,hwnd);
}
}
/// makes a function that matches against window text
// @param text
// @function make_name_matcher
/// makes a function that matches against window class name
// @param text
// @function make_class_matcher
/// find a window using a condition function.
// @param match will return true when its argument is the desired window
// @return @{Window}
// @function find_window_ex
/// return all windows matching a condition.
// @param match will return true when its argument is the desired window
// @return a list of window objects
// @function find_all_windows
/// find a window matching the given text.
// @param text the pattern to match against the caption
// @return a window object.
// @function find_window_match
/// current foreground window.
// An example of setting the caption is @{caption.lua}
// @return @{Window}
// @function get_foreground_window
def get_foreground_window() {
return push_new_Window(L, GetForegroundWindow());
}
/// the desktop window.
// @usage winapi.get_desktop_window():get_bounds()
// @return @{Window}
// @function get_desktop_window
def get_desktop_window() {
return push_new_Window(L, GetDesktopWindow());
}
/// a Window object from a handle
// @param a Windows nandle
// @return @{Window}
// @function window_from_handle
def window_from_handle(Int hwnd) {
return push_new_Window(L, (HWND)hwnd);
}
/// enumerate over all top-level windows.
// @param callback a function to receive each window object
// @function enum_windows
def enum_windows(Value callback) {
Ref ref;
sL = L;
ref = make_ref(L,callback);
EnumWindows(&enum_callback,ref);
release_ref(L,ref);
return 0;
}
/// route callback dispatch through a message window.
// You need to do this when using Winapi in a GUI application,
// since it ensures that Lua callbacks happen in the GUI thread.
// @function use_gui
def use_gui() {
make_message_window();
return 0;
}
static INPUT *add_input(INPUT *pi, WORD vkey, BOOL up) {
pi->type = INPUT_KEYBOARD;
pi->ki.dwFlags = up ? KEYEVENTF_KEYUP : 0;
pi->ki.wVk = vkey;
return pi+1;
}
// The Windows SendInput() is a low-level function, and you have to
// simulate things like uppercase directly. Repeated characters need
// an explicit 'key up' keystroke to work.
// see http://stackoverflow.com/questions/2167156/sendinput-isnt-sending-the-correct-shifted-characters
// this is a case where we have to convert the parameter directly, since
// it may be an integer (virtual key code) or string of characters.
/// send a string or virtual key to the active window.
// @{input.lua} shows launching a process, waiting for it to be
// ready, and sending it some keys
// @param text either a key (like winapi.VK_SHIFT) or a string
// @return number of keys sent, or nil if an error
// @return any error string
// @function send_to_window
def send_to_window () {
const char *text;
int vkey, len = MAX_KEYS;
UINT res;
SHORT last_vk = 0;
INPUT *input, *pi;
if (lua_isnumber(L,1)) {
INPUT inp;
ZeroMemory(&inp,sizeof(INPUT));
vkey = lua_tointeger(L,1);
add_input(&inp,vkey,lua_toboolean(L,2));
SendInput(1,&inp,sizeof(INPUT));
return 0;
} else {
text = lua_tostring(L,1);
if (text == NULL) {
return push_error_msg(L,"not a string or number");
}
}
input = (INPUT *)malloc(sizeof(INPUT)*len);
pi = input;
ZeroMemory(input, sizeof(INPUT)*len);
for(; *text; ++text) {
SHORT vk = VkKeyScan(*text);
if (last_vk == vk) {
pi = add_input(pi,last_vk & 0xFF,TRUE);
}
if (vk & 0x100) pi = add_input(pi,VK_SHIFT,FALSE);
pi = add_input(pi,vk & 0xFF,FALSE);
if (vk & 0x100) pi = add_input(pi,VK_SHIFT,TRUE);
last_vk = vk;
}
res = SendInput(((DWORD_PTR)pi-(DWORD_PTR)input)/sizeof(INPUT), input, sizeof(INPUT));
free(input);
if (res > 0) {
lua_pushinteger(L,res);
return 1;
} else {
return push_error(L);
}
return 0;
}
/// tile a group of windows.
// @param parent @{Window} (can use the desktop)
// @param horiz tile vertically by default
// @param kids a table of window objects
// @param bounds a bounds table (left,top,right,bottom) - can be nil
// @function tile_windows
def tile_windows(Window parent, Boolean horiz, Value kids, Value bounds) {
RECT rt;
HWND *kids_arr;
int i,n_kids;
LPRECT lpRect = NULL;
if (! lua_isnoneornil(L,bounds)) {
lua_pushvalue(L,bounds);
Int_get(rt.left,"left");
Int_get(rt.top,"top");
Int_get(rt.right,"right");
Int_get(rt.bottom,"bottom");
lua_pop(L,1);
lpRect = &rt;
}
n_kids = lua_objlen(L,kids);
kids_arr = (HWND *)malloc(sizeof(HWND)*n_kids);
for (i = 0; i < n_kids; ++i) {
Window *w;
lua_rawgeti(L,kids,i+1);
w = Window_arg(L,-1);
kids_arr[i] = w->hwnd;
}
TileWindows(parent->hwnd,horiz ? MDITILE_HORIZONTAL : MDITILE_VERTICAL, lpRect, n_kids, kids_arr);
free(kids_arr);
return 0;
}
/// Miscellaneous functions.
// @section miscellaneous
static int push_new_File(lua_State *L,HANDLE hread, HANDLE hwrite);
/// sleep and use no processing time.
// @param millisec sleep period
// @function sleep
def sleep(Int millisec) {
release_mutex();
Sleep(millisec);
lock_mutex();
return 0;
}
/// show a message box.
// @param caption for dialog
// @param msg the message
// @param btns (default 'ok') one of 'ok','ok-cancel','yes','yes-no',
// "abort-retry-ignore", "retry-cancel", "yes-no-cancel"
// @param icon (default 'information') one of 'information','question','warning','error'
// @return a string giving the pressed button: one of 'ok','yes','no','cancel',
// 'try','abort' and 'retry'
// @see message.lua
// @function show_message
def show_message(Str caption, Str msg, Str btns = "ok", Str icon = "information") {
int res, type;
WCHAR capb [512];
type = mb_const(btns) | mb_const(icon);
wstring_buff(caption,capb,sizeof(capb));
res = MessageBoxW( NULL, wstring(msg), capb, type);
lua_pushstring(L,mb_result(res));
return 1;
}
/// make a beep sound.
// @param type (default 'ok'); one of 'information','question','warning','error'
// @function beep
def beep (Str icon = "ok") {
return push_bool(L, MessageBeep(mb_const(icon)));
}
/// copy a file.
// @param src source file
// @param dest destination file
// @param fail_if_exists if true, then cannot copy onto existing file
// @function copy_file
def copy_file(Str src, Str dest, Int fail_if_exists = 0) {
return push_bool(L, CopyFile(src,dest,fail_if_exists));
}
/// output text to the system debugger.
// A uility such as [DebugView](http://technet.microsoft.com/en-us/sysinternals/bb896647)
// can show the output
// @param str text
// @function output_debug_string
def output_debug_string(Str str) {
OutputDebugString(str);
return 0;
}
/// move a file.
// @param src source file
// @param dest destination file
// @function move_file
def move_file(Str src, Str dest) {
return push_bool(L, MoveFile(src,dest));
}
#define wconv(name) (name ? wstring_buff(name,w##name,sizeof(w##name)) : NULL)
/// execute a shell command.
// @param verb the action (e.g. 'open' or 'edit') can be nil.
// @param file the command
// @param parms any parameters (optional)
// @param dir the working directory (optional)
// @param show the window show flags (default is SW_SHOWNORMAL)
// @function shell_exec
def shell_exec(StrNil verb, Str file, StrNil parms, StrNil dir, Int show=SW_SHOWNORMAL) {
WCHAR wverb[128], wfile[MAX_WPATH], wdir[MAX_WPATH], wparms[MAX_WPATH];
int res = (DWORD_PTR)ShellExecuteW(NULL,wconv(verb),wconv(file),wconv(parms),wconv(dir),show) > 32;
return push_bool(L, res);
}
/// copy text onto the clipboard.
// @param text the text
// @function set_clipboard
def set_clipboard(Str text) {
HGLOBAL glob;
LPWSTR p;
int bufsize = 3*strlen(text);
if (! OpenClipboard(NULL)) {
return push_perror(L,"openclipboard");
}
EmptyClipboard();
glob = GlobalAlloc(GMEM_MOVEABLE, bufsize);
p = (LPWSTR)GlobalLock(glob);
wstring_buff(text,p,bufsize);
GlobalUnlock(glob);
if (SetClipboardData(CF_UNICODETEXT,glob) == NULL) {
CloseClipboard();
return push_error(L);
}
CloseClipboard();
return 0;
}
/// get the text on the clipboard.
// @return the text
// @function get_clipboard
def get_clipboard() {
HGLOBAL glob;
LPCWSTR p;
if (! OpenClipboard(NULL)) {
return push_perror(L,"openclipboard");
}
glob = GetClipboardData(CF_UNICODETEXT);
if (glob == NULL) {
CloseClipboard();
return push_error(L);
}
p = GlobalLock(glob);
push_wstring(L,p);
GlobalUnlock(glob);
CloseClipboard();
return 1;
}
/// open console i/o.
// @return @{File}
// @function get_console
def get_console() {
HANDLE w = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE r = GetStdHandle(STD_INPUT_HANDLE);
return push_new_File(L,r,w);
}
def pipe() {
HANDLE hRead, hWrite;
if (CreatePipe(&hRead,&hWrite,NULL,0) != 0) {
push_new_File(L,hRead,NULL);
push_new_File(L,NULL,hWrite);
return 2;
} else {
return push_error(L);
}
}
/// open a serial port for reading and writing.
// @param defn a string as used by the [mode command](http://technet.microsoft.com/en-us/library/cc732236%28WS.10%29.aspx)
// @return @{File}
// @function open_serial
def open_serial(Str defn) {
DCB dcb = {0};
char port[20];
HANDLE hSerial;
const char *p = defn;
char *q = port;
for (; *p != ' '; p++) {
*q++ = *p;
}
*q = '\0';
dcb.DCBlength = sizeof(dcb);
hSerial = CreateFile(port,GENERIC_READ | GENERIC_WRITE, 0, 0,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hSerial == INVALID_HANDLE_VALUE) {
return push_perror(L,"createfile");
}
GetCommState(hSerial,&dcb);
if (! BuildCommDCB(defn,&dcb)) {
CloseHandle(hSerial);
return push_perror(L,"buildcom");
}
if (! SetCommState(hSerial,&dcb)) {
CloseHandle(hSerial);
return push_perror(L,"setcomm");
}
return push_new_File(L,hSerial,hSerial);
}
static int push_wait_result(lua_State *L, DWORD res) {
if (res == WAIT_OBJECT_0) {
lua_pushvalue(L,1);
lua_pushliteral(L,"OK");
return 2;
} else if (res == WAIT_TIMEOUT) {
lua_pushvalue(L,1);
lua_pushliteral(L,"TIMEOUT");
return 2;
} else {
return push_error(L);
}
}
static int wait_single(HANDLE h, int timeout) {
DWORD res;
release_mutex();
res = WaitForSingleObject (h, timeout);
lock_mutex();
return res;
}
static int push_wait(lua_State *L, HANDLE h, int timeout) {
return push_wait_result(L,wait_single(h,timeout));
}
static int push_wait_async(lua_State *L, HANDLE h, int timeout, int callback);
/// The Event class.
// @type Event
class Event {
HANDLE hEvent;
constructor(HANDLE h) {
this->hEvent = h;
}
/// wait for this event to be signalled.
// @param timeout optional timeout in millisec; defaults to waiting indefinitely.
// @return this event object
// @return either "OK" or "TIMEOUT"
// @function wait
def wait(Int timeout=0) {
return push_wait(L,this->hEvent, TIMEOUT(timeout));
}
/// run callback when this process is finished.
// @param callback the callback
// @param timeout optional timeout in millisec; defaults to waiting indefinitely.
// @return this process object
// @return either "OK" or "TIMEOUT"
// @function wait_async
def wait_async(Value callback, Int timeout = 0) {
return push_wait_async(L,this->hEvent, TIMEOUT(timeout), callback);
}
def signal() {
SetEvent(this->hEvent);
return 0;
}
def __gc() {
CloseHandle(this->hEvent);
return 0;
}
}
/// The Mutex class.
// @type Mutex
class Mutex {
HANDLE hMutex;
constructor (HANDLE h) {
this->hMutex = h;
}
def lock() {
WaitForSingleObject(this->hMutex,INFINITE);
return 0;
}
def release() {
ReleaseMutex(this->hMutex);
return 0;
}
def __gc() {
CloseHandle(this->hMutex);
return 0;
}
}
static int _event_count = 1;
/// create a new @{Event} object.
// @param name string (optional)
// @return @{Event}, or nil, error.
def event (Str name="?") {
HANDLE hEvent;
char buff[MAX_PATH];
if (strcmp(name,"?")==0) {
sprintf(buff,"_event_%d",_event_count++);
name = buff;
}
hEvent = CreateEvent (NULL,0,0,name);
if (hEvent == NULL) {
return push_error(L);
} else {
return push_new_Event(L,hEvent);
}
}
/// create a new @{Mutex} object.
// @param name string (optional)
// @return @{Mutex}, or nil, error.
def mutex(Str name="") {
return push_new_Mutex(L,CreateMutex(NULL,FALSE,*name==0 ? NULL : name));
}
/// A class representing a Windows process.
// this example was [helpful](http://msdn.microsoft.com/en-us/library/ms682623%28VS.85%29.aspx)
// @type Process
class Process {
HANDLE hProcess;
int pid;
constructor(Int pid, HANDLE ph) {
if (ph) {
this->pid = pid;
this->hProcess = ph;
} else {
this->pid = pid;
this->hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ | PROCESS_TERMINATE,
FALSE, pid );
if (!this->hProcess) {
this->hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, pid );
}
}
}
/// get the name of the process.
// @param full true if you want the full path; otherwise returns the base name.
// @function get_process_name
def get_process_name(Boolean full) {
HMODULE hMod;
DWORD cbNeeded;
wchar_t modname[MAX_PATH];
if (EnumProcessModules(this->hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
if (full) {
GetModuleFileNameExW(this->hProcess, hMod, modname, sizeof(modname));
} else {
GetModuleBaseNameW(this->hProcess, hMod, modname, sizeof(modname));
}
return push_wstring(L,modname);
} else {
return push_error(L);
}
}
/// get the the pid of the process.
// @function get_pid
def get_pid() {
lua_pushnumber(L, this->pid);
return 1;
}
/// kill the process.
// @{test-spawn.lua} kills a launched process after a certain amount of output.
// @function kill
def kill() {
TerminateProcess(this->hProcess,0);
return 0;
}
/// get the working size of the process.
// @return minimum working set size
// @return maximum working set size.
// @function get_working_size
def get_working_size() {
SIZE_T minsize, maxsize;
GetProcessWorkingSetSize(this->hProcess,&minsize,&maxsize);
lua_pushnumber(L,minsize/1024);
lua_pushnumber(L,maxsize/1024);
return 2;
}
/// get the start time of this process.
// @return a table in the same format as os.time() and os.date() expects.
// @function get_start_time
def get_start_time() {
FILETIME create,exit,kernel,user,local;
SYSTEMTIME time;
GetProcessTimes(this->hProcess,&create,&exit,&kernel,&user);
FileTimeToLocalFileTime(&create,&local);
FileTimeToSystemTime(&local,&time);
#define set(name,val) lua_pushinteger(L,val); lua_setfield(L,-2,#name);
lua_newtable(L);
set(year,time.wYear);
set(month,time.wMonth);
set(day,time.wDay);
set(hour,time.wHour);
set(min,time.wMinute);
set(sec,time.wSecond);
#undef set
return 1;
}
// MS likes to be different: the 64-bit value encoded in FILETIME
// is defined as the number of 100-nsec intervals since Jan 1, 1601 UTC
static double fileTimeToMillisec(FILETIME *ft) {
ULARGE_INTEGER ui;
ui.LowPart = ft->dwLowDateTime;
ui.HighPart = ft->dwHighDateTime;
return (double) (ui.QuadPart/10000);
}
/// elapsed run time of this process.
// @return user time in msec
// @return system time in msec
// @function get_run_times
def get_run_times() {
FILETIME create,exit,kernel,user;
GetProcessTimes(this->hProcess,&create,&exit,&kernel,&user);
lua_pushnumber(L,fileTimeToMillisec(&user));
lua_pushnumber(L,fileTimeToMillisec(&kernel));
return 2;
}
/// wait for this process to finish.
// @param timeout optional timeout in millisec; defaults to waiting indefinitely.
// @return this process object
// @return either "OK" or "TIMEOUT"
// @function wait
def wait(Int timeout = 0) {
return push_wait(L,this->hProcess, TIMEOUT(timeout));
}
/// run callback when this process is finished.
// @param callback the callback
// @param timeout optional timeout in millisec; defaults to waiting indefinitely.
// @return this process object
// @return either "OK" or "TIMEOUT"
// @function wait_async
def wait_async(Value callback, Int timeout = 0) {
return push_wait_async(L,this->hProcess, TIMEOUT(timeout), callback);
}
/// wait for this process to become idle and ready for input.
// Only makes sense for processes with windows (will return immediately if not)
// @param timeout optional timeout in millisec
// @return this process object
// @return either "OK" or "TIMEOUT"
// @function wait_for_input_idle
def wait_for_input_idle (Int timeout = 0) {
return push_wait_result(L, WaitForInputIdle(this->hProcess, TIMEOUT(timeout)));
}
/// exit code of this process.
// (Only makes sense if the process has in fact finished.)
// @return exit code
// @function get_exit_code
def get_exit_code() {
DWORD code;
GetExitCodeProcess(this->hProcess, &code);
lua_pushinteger(L,code);
return 1;
}