/
script.cpp
14030 lines (12816 loc) · 634 KB
/
script.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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
/*
AutoHotkey
Copyright 2003-2009 Chris Mallett (support@autohotkey.com)
This program 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
of the License, or (at your option) any later version.
This program 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.
*/
#include "stdafx.h" // pre-compiled headers
#include "script.h"
#include "globaldata.h" // for a lot of things
#include "util.h" // for strlcpy() etc.
#include "mt19937ar-cok.h" // for random number generator
#include "window.h" // for a lot of things
#include "application.h" // for MsgSleep()
#include "TextIO.h"
// Globals that are for only this module (mostly):
static ExprOpFunc g_ObjGetInPlace(Op_ObjGetInPlace, IT_GET);
static ExprOpFunc g_ObjNew(Op_ObjNew, IT_CALL);
static ExprOpFunc g_ObjPreInc(Op_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(Op_ObjIncDec, SYM_PRE_DECREMENT)
, g_ObjPostInc(Op_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(Op_ObjIncDec, SYM_POST_DECREMENT);
ExprOpFunc g_ObjCall(Op_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp.
ExprOpFunc g_ObjGet(Op_ObjInvoke, IT_GET), g_ObjSet(Op_ObjInvoke, IT_SET); // Also needed in script_object_bif.cpp.
ExprOpFunc g_FuncClose(BIF_Func, FID_FuncClose);
#define NA MAX_FUNCTION_PARAMS
#define BIFn(name, minp, maxp, bif, ...) {_T(#name), bif, minp, maxp, FID_##name, __VA_ARGS__}
#define BIF1(name, minp, maxp, ...) {_T(#name), BIF_##name, minp, maxp, 0, __VA_ARGS__}
// The following array defines all built-in functions, their min and max parameter counts,
// and which real C++ function contains their implementation. The macros above are used to
// reduce repetition and implement code-sharing: BIFs which share a C++ function are assigned
// an integer ID, defined in the BuiltInFunctionID enum. Items must be in alphabetical order.
FuncEntry g_BIF[] =
{
BIF1(Abs, 1, 1),
BIFn(ACos, 1, 1, BIF_ASinACos),
BIF1(Array, 0, NA),
BIFn(ASin, 1, 1, BIF_ASinACos),
BIF1(ATan, 1, 1),
BIF1(CallbackCreate, 1, 3),
BIF1(CallbackFree, 1, 1),
BIF1(CaretGetPos, 0, 2, {1, 2}),
BIFn(Ceil, 1, 1, BIF_FloorCeil),
BIF1(Chr, 1, 1),
BIF1(ClipboardAll, 0, 2),
BIFn(ClipWait, 0, 2, BIF_Wait),
BIF1(ComObjActive, 1, 1),
BIF1(ComObjArray, 2, 9),
BIF1(ComObjConnect, 1, 2),
BIF1(ComObjCreate, 1, 2),
BIF1(ComObject, 1, 3),
BIF1(ComObjError, 0, 1),
BIF1(ComObjFlags, 1, 3),
BIF1(ComObjGet, 1, 1),
BIF1(ComObjQuery, 2, 3),
BIFn(ComObjType, 1, 2, BIF_ComObjTypeOrValue),
BIFn(ComObjValue, 1, 1, BIF_ComObjTypeOrValue),
BIFn(ControlAddItem, 2, 6, BIF_Control),
BIFn(ControlChoose, 2, 6, BIF_Control),
BIFn(ControlChooseString, 2, 6, BIF_Control),
BIF1(ControlClick, 0, 8),
BIFn(ControlDeleteItem, 2, 6, BIF_Control),
BIFn(ControlEditPaste, 2, 6, BIF_Control),
BIFn(ControlFindItem, 2, 6, BIF_ControlGet),
BIF1(ControlFocus, 1, 5),
BIFn(ControlGetChecked, 1, 5, BIF_ControlGet),
BIFn(ControlGetChoice, 1, 5, BIF_ControlGet),
BIF1(ControlGetClassNN, 1, 5),
BIFn(ControlGetCurrentCol, 1, 5, BIF_ControlGet),
BIFn(ControlGetCurrentLine, 1, 5, BIF_ControlGet),
BIFn(ControlGetEnabled, 1, 5, BIF_ControlGet),
BIFn(ControlGetExStyle, 1, 5, BIF_ControlGet),
BIF1(ControlGetFocus, 0, 4),
BIFn(ControlGetHwnd, 1, 5, BIF_ControlGet),
BIFn(ControlGetLine, 2, 6, BIF_ControlGet),
BIFn(ControlGetLineCount, 1, 5, BIF_ControlGet),
BIFn(ControlGetList, 0, 6, BIF_ControlGet),
BIF1(ControlGetPos, 0, 9, {1, 2, 3, 4}),
BIFn(ControlGetSelected, 1, 5, BIF_ControlGet),
BIFn(ControlGetStyle, 1, 5, BIF_ControlGet),
BIFn(ControlGetTab, 1, 5, BIF_ControlGet),
BIF1(ControlGetText, 1, 5),
BIFn(ControlGetVisible, 1, 5, BIF_ControlGet),
BIFn(ControlHide, 1, 5, BIF_Control),
BIFn(ControlHideDropDown, 1, 5, BIF_Control),
BIF1(ControlMove, 0, 9),
BIFn(ControlSend, 1, 6, BIF_ControlSend),
BIFn(ControlSendText, 1, 6, BIF_ControlSend),
BIFn(ControlSetChecked, 2, 6, BIF_Control),
BIFn(ControlSetEnabled, 2, 6, BIF_Control),
BIFn(ControlSetExStyle, 2, 6, BIF_Control),
BIFn(ControlSetStyle, 2, 6, BIF_Control),
BIFn(ControlSetTab, 2, 6, BIF_Control),
BIF1(ControlSetText, 2, 6),
BIFn(ControlShow, 1, 5, BIF_Control),
BIFn(ControlShowDropDown, 1, 5, BIF_Control),
BIF1(Cos, 1, 1),
BIF1(DateAdd, 3, 3),
BIF1(DateDiff, 3, 3),
BIFn(DirExist, 1, 1, BIF_FileExist),
BIF1(DirSelect, 0, 3),
BIF1(DllCall, 1, NA),
BIFn(DriveEject, 0, 2, BIF_Drive),
BIFn(DriveGetCapacity, 1, 1, BIF_DriveGet),
BIFn(DriveGetFilesystem, 1, 1, BIF_DriveGet),
BIFn(DriveGetLabel, 1, 1, BIF_DriveGet),
BIFn(DriveGetList, 0, 1, BIF_DriveGet),
BIFn(DriveGetSerial, 1, 1, BIF_DriveGet),
BIFn(DriveGetSpaceFree, 1, 1, BIF_DriveGet),
BIFn(DriveGetStatus, 1, 1, BIF_DriveGet),
BIFn(DriveGetStatusCD, 0, 1, BIF_DriveGet),
BIFn(DriveGetType, 1, 1, BIF_DriveGet),
BIFn(DriveLock, 1, 1, BIF_Drive),
BIFn(DriveSetLabel, 1, 2, BIF_Drive),
BIFn(DriveUnlock, 1, 1, BIF_Drive),
BIFn(EnvGet, 1, 1, BIF_Env),
BIFn(EnvSet, 1, 2, BIF_Env),
BIF1(Exception, 1, 3),
BIF1(Exp, 1, 1),
BIF1(FileAppend, 1, 3),
BIFn(FileExist, 1, 1, BIF_FileExist),
BIF1(FileGetAttrib, 0, 1),
BIF1(FileGetSize, 0, 2),
BIF1(FileGetTime, 0, 2),
BIF1(FileGetVersion, 0, 1),
BIF1(FileOpen, 2, 3),
BIF1(FileRead, 1, 2),
BIF1(FileSelect, 0, 4),
BIF1(Float, 1, 1),
BIFn(Floor, 1, 1, BIF_FloorCeil),
BIF1(Format, 1, NA),
BIF1(FormatTime, 0, 2),
BIF1(Func, 1, 1),
BIFn(GetKeyName, 1, 1, BIF_GetKeyName),
BIFn(GetKeySC, 1, 1, BIF_GetKeyName),
BIF1(GetKeyState, 1, 2),
BIFn(GetKeyVK, 1, 1, BIF_GetKeyName),
BIF1(GuiCreate, 0, 3),
BIF1(GuiCtrlFromHwnd, 1, 1),
BIF1(GuiFromHwnd, 1, 2),
BIF1(Hotkey, 1, 3),
BIF1(Hotstring, 1, 3),
BIF1(IL_Add, 2, 4),
BIF1(IL_Create, 0, 3),
BIF1(IL_Destroy, 1, 1),
BIF1(IniRead, 1, 4),
BIFn(Input, 0, 3, BIF_Input),
BIF1(InputBox, 0, 4),
BIFn(InputEnd, 0, 0, BIF_Input),
BIF1(InStr, 2, 5),
BIF1(Integer, 1, 1),
BIF1(IsByRef, 1, 1, {1}),
BIF1(IsFunc, 1, 1),
BIF1(IsLabel, 1, 1),
BIF1(IsObject, 1, NA),
BIFn(KeyWait, 1, 2, BIF_Wait),
BIFn(Ln, 1, 1, BIF_SqrtLogLn),
BIF1(LoadPicture, 1, 3),
BIFn(Log, 1, 1, BIF_SqrtLogLn),
BIFn(LTrim, 1, 2, BIF_Trim),
BIFn(Max, 1, NA, BIF_MinMax),
BIFn(MenuBarCreate, 0, 0, BIF_Menu),
BIFn(MenuCreate, 0, 0, BIF_Menu),
BIFn(MenuFromHandle, 1, 1, BIF_Menu),
BIFn(Min, 1, NA, BIF_MinMax),
BIF1(Mod, 2, 2),
BIFn(MonitorGet, 0, 5, BIF_MonitorGet, {2, 3, 4, 5}),
BIFn(MonitorGetCount, 0, 0, BIF_MonitorGet),
BIFn(MonitorGetName, 0, 1, BIF_MonitorGet),
BIFn(MonitorGetPrimary, 0, 0, BIF_MonitorGet),
BIFn(MonitorGetWorkArea, 0, 5, BIF_MonitorGet, {2, 3, 4, 5}),
BIF1(MsgBox, 0, 3),
BIF1(NumGet, 1, 3),
BIF1(NumPut, 2, 4),
BIFn(ObjAddRef, 1, 1, BIF_ObjAddRefRelease),
BIF1(ObjBindMethod, 1, NA),
BIFn(ObjClone, 1, 1, BIF_ObjXXX),
BIFn(ObjCount, 1, 1, BIF_ObjXXX),
BIFn(ObjDelete, 2, 3, BIF_ObjXXX),
BIF1(Object, 0, NA),
BIFn(ObjGetAddress, 2, 2, BIF_ObjXXX),
BIFn(ObjGetBase, 1, 1, BIF_ObjBase),
BIFn(ObjGetCapacity, 1, 2, BIF_ObjXXX),
BIFn(ObjHasKey, 2, 2, BIF_ObjXXX),
BIFn(ObjInsertAt, 3, NA, BIF_ObjXXX),
BIFn(ObjLength, 1, 1, BIF_ObjXXX),
BIFn(ObjMaxIndex, 1, 1, BIF_ObjXXX),
BIFn(ObjMinIndex, 1, 1, BIF_ObjXXX),
BIFn(ObjNewEnum, 1, 1, BIF_ObjXXX),
BIFn(ObjPop, 1, 1, BIF_ObjXXX),
BIFn(ObjPush, 2, NA, BIF_ObjXXX),
BIFn(ObjRawGet, 2, 2, BIF_ObjRaw),
BIFn(ObjRawSet, 3, 3, BIF_ObjRaw),
BIFn(ObjRelease, 1, 1, BIF_ObjAddRefRelease),
BIFn(ObjRemoveAt, 2, 3, BIF_ObjXXX),
BIFn(ObjSetBase, 2, 2, BIF_ObjBase),
BIFn(ObjSetCapacity, 2, 3, BIF_ObjXXX),
BIFn(OnClipboardChange, 1, 2, BIF_On),
BIFn(OnError, 1, 2, BIF_On),
BIFn(OnExit, 1, 2, BIF_On),
BIF1(OnMessage, 2, 3),
BIF1(Ord, 1, 1),
BIF1(PixelGetColor, 2, 3),
BIFn(PostMessage, 1, 8, BIF_PostSendMessage),
BIFn(ProcessClose, 1, 1, BIF_Process),
BIFn(ProcessExist, 0, 1, BIF_Process),
BIF1(ProcessSetPriority, 1, 2),
BIFn(ProcessWait, 1, 2, BIF_Process),
BIFn(ProcessWaitClose, 1, 2, BIF_Process),
BIFn(Random, 0, 2, BIF_Random),
BIFn(RandomSeed, 1, 1, BIF_Random),
BIFn(RegDelete, 0, 2, BIF_Reg),
BIFn(RegDeleteKey, 0, 1, BIF_Reg),
BIFn(RegExMatch, 2, 4, BIF_RegEx, {3}),
BIFn(RegExReplace, 2, 6, BIF_RegEx, {4}),
BIFn(RegRead, 0, 2, BIF_Reg),
BIFn(RegWrite, 0, 4, BIF_Reg),
BIF1(Round, 1, 2),
BIFn(RTrim, 1, 2, BIF_Trim),
BIFn(RunWait, 1, 4, BIF_Wait, {4}),
BIFn(SendMessage, 1, 9, BIF_PostSendMessage),
BIF1(SetTimer, 0, 3),
BIF1(Sin, 1, 1),
BIF1(Sort, 1, 2),
BIFn(SoundGet, 0, 3, BIF_Sound),
BIFn(SoundSet, 1, 4, BIF_Sound),
BIFn(Sqrt, 1, 1, BIF_SqrtLogLn),
BIF1(StatusBarGetText, 0, 5),
BIFn(StrGet, 1, 3, BIF_StrGetPut),
BIF1(String, 1, 1),
BIF1(StrLen, 1, 1),
BIFn(StrLower, 1, 2, BIF_StrCase),
BIFn(StrPut, 1, 4, BIF_StrGetPut),
BIF1(StrReplace, 2, 5, {4}),
BIF1(StrSplit, 1, 4),
BIFn(StrUpper, 1, 2, BIF_StrCase),
BIF1(SubStr, 2, 3),
BIF1(SysGet, 1, 1),
BIF1(SysGetIPAddresses, 0, 0),
BIF1(Tan, 1, 1),
BIF1(TraySetIcon, 0, 3),
BIFn(Trim, 1, 2, BIF_Trim),
BIF1(Type, 1, 1),
BIF1(VarSetCapacity, 1, 3, {1}),
BIFn(WinActive, 0, 4, BIF_WinExistActive),
BIFn(WinExist, 0, 4, BIF_WinExistActive),
BIF1(WinGetClass, 0, 4),
BIFn(WinGetClientPos, 0, 8, BIF_WinGetPos, {1, 2, 3, 4}),
BIFn(WinGetControls, 0, 4, BIF_WinGet),
BIFn(WinGetControlsHwnd, 0, 4, BIF_WinGet),
BIFn(WinGetCount, 0, 4, BIF_WinGet),
BIFn(WinGetExStyle, 0, 4, BIF_WinGet),
BIFn(WinGetID, 0, 4, BIF_WinGet),
BIFn(WinGetIDLast, 0, 4, BIF_WinGet),
BIFn(WinGetList, 0, 4, BIF_WinGet),
BIFn(WinGetMinMax, 0, 4, BIF_WinGet),
BIFn(WinGetPID, 0, 4, BIF_WinGet),
BIFn(WinGetPos, 0, 8, BIF_WinGetPos, {1, 2, 3, 4}),
BIFn(WinGetProcessName, 0, 4, BIF_WinGet),
BIFn(WinGetProcessPath, 0, 4, BIF_WinGet),
BIFn(WinGetStyle, 0, 4, BIF_WinGet),
BIF1(WinGetText, 0, 4),
BIF1(WinGetTitle, 0, 4),
BIFn(WinGetTransColor, 0, 4, BIF_WinGet),
BIFn(WinGetTransparent, 0, 4, BIF_WinGet),
BIFn(WinMoveBottom, 0, 4, BIF_WinMoveTopBottom),
BIFn(WinMoveTop, 0, 4, BIF_WinMoveTopBottom),
BIF1(WinRedraw, 0, 4),
BIFn(WinSetAlwaysOnTop, 0, 5, BIF_WinSet),
BIFn(WinSetEnabled, 1, 5, BIF_WinSet),
BIFn(WinSetExStyle, 1, 5, BIF_WinSet),
BIFn(WinSetRegion, 0, 5, BIF_WinSet),
BIFn(WinSetStyle, 1, 5, BIF_WinSet),
BIFn(WinSetTransColor, 1, 5, BIF_WinSet),
BIFn(WinSetTransparent, 1, 5, BIF_WinSet),
BIFn(WinWait, 0, 5, BIF_Wait),
BIFn(WinWaitActive, 0, 5, BIF_Wait),
BIFn(WinWaitClose, 0, 5, BIF_Wait),
BIFn(WinWaitNotActive, 0, 5, BIF_Wait),
};
#undef NA
#undef BIFn
#undef BIF1
#define VF(name, fn) { _T(#name), fn, NULL }
#define A_x(name, fn) { _T(#name), fn, NULL }
#define A_(name) A_x(name, BIV_##name)
#define A_wx(name, fnget, fnset) { _T(#name), fnget, fnset }
#define A_w(name) A_wx(name, BIV_##name, BIV_##name##_Set)
// IMPORTANT: Both of the following arrays must be kept in alphabetical order
// for binary search to work. See Script::GetBuiltInVar for further comments.
// g_BIV: All built-in vars not beginning with "A_". Keeping these separate allows
// the search to be limited to just these few whenever the var name does not begin
// with "A_", as for most user-defined variables. This helps average-case performance.
VarEntry g_BIV[] =
{
VF(Clipboard, (BuiltInVarType)VAR_CLIPBOARD),
VF(False, BIV_True_False),
VF(ProgramFiles, BIV_SpecialFolderPath), // v1.0.43.08: Added to ease the transition to #NoEnv.,
VF(True, BIV_True_False)
};
// g_BIV_A: All built-in vars beginning with "A_". The prefix is omitted from each
// name to reduce code size and speed up the comparisons.
VarEntry g_BIV_A[] =
{
A_(AhkPath),
A_(AhkVersion),
A_w(AllowMainWindow),
A_x(AppData, BIV_SpecialFolderPath),
A_x(AppDataCommon, BIV_SpecialFolderPath),
A_x(ComputerName, BIV_UserName_ComputerName),
A_(ComSpec),
A_wx(ControlDelay, BIV_xDelay, BIV_xDelay_Set),
A_wx(CoordModeCaret, BIV_CoordMode, BIV_CoordMode_Set),
A_wx(CoordModeMenu, BIV_CoordMode, BIV_CoordMode_Set),
A_wx(CoordModeMouse, BIV_CoordMode, BIV_CoordMode_Set),
A_wx(CoordModePixel, BIV_CoordMode, BIV_CoordMode_Set),
A_wx(CoordModeToolTip, BIV_CoordMode, BIV_CoordMode_Set),
A_(Cursor),
A_x(DD, BIV_DateTime),
A_x(DDD, BIV_MMM_DDD),
A_x(DDDD, BIV_MMM_DDD),
A_w(DefaultMouseSpeed),
A_x(Desktop, BIV_SpecialFolderPath),
A_x(DesktopCommon, BIV_SpecialFolderPath),
A_w(DetectHiddenText),
A_w(DetectHiddenWindows),
A_(EndChar),
A_w(EventInfo), // It's called "EventInfo" vs. "GuiEventInfo" because it applies to non-Gui events such as OnClipboardChange.,
A_w(FileEncoding),
A_x(Hour, BIV_DateTime),
A_(IconFile),
A_w(IconHidden),
A_(IconNumber),
A_w(IconTip),
A_wx(Index, BIV_LoopIndex, BIV_LoopIndex_Set),
A_(InitialWorkingDir),
A_(Is64bitOS),
A_(IsAdmin),
A_(IsCompiled),
A_(IsCritical),
A_(IsPaused),
A_(IsSuspended),
A_(IsUnicode),
A_wx(KeyDelay, BIV_xDelay, BIV_xDelay_Set),
A_wx(KeyDelayPlay, BIV_xDelay, BIV_xDelay_Set),
A_wx(KeyDuration, BIV_xDelay, BIV_xDelay_Set),
A_wx(KeyDurationPlay, BIV_xDelay, BIV_xDelay_Set),
A_(Language),
A_w(LastError),
A_(LineFile),
A_(LineNumber),
A_w(ListLines),
A_(LoopField),
A_(LoopFileAttrib),
A_(LoopFileDir),
A_(LoopFileExt),
A_(LoopFileFullPath),
A_(LoopFileName),
A_(LoopFilePath),
A_(LoopFileShortName),
A_(LoopFileShortPath),
A_x(LoopFileSize, BIV_LoopFileSize),
A_x(LoopFileSizeKB, BIV_LoopFileSize),
A_x(LoopFileSizeMB, BIV_LoopFileSize),
A_x(LoopFileTimeAccessed, BIV_LoopFileTime),
A_x(LoopFileTimeCreated, BIV_LoopFileTime),
A_x(LoopFileTimeModified, BIV_LoopFileTime),
A_(LoopReadLine),
A_(LoopRegKey),
A_(LoopRegName),
A_(LoopRegTimeModified),
A_(LoopRegType),
A_x(MDay, BIV_DateTime),
A_x(Min, BIV_DateTime),
A_x(MM, BIV_DateTime),
A_x(MMM, BIV_MMM_DDD),
A_x(MMMM, BIV_MMM_DDD),
A_x(Mon, BIV_DateTime),
A_wx(MouseDelay, BIV_xDelay, BIV_xDelay_Set),
A_wx(MouseDelayPlay, BIV_xDelay, BIV_xDelay_Set),
A_x(MSec, BIV_DateTime),
A_(MyDocuments),
A_x(Now, BIV_Now),
A_x(NowUTC, BIV_Now),
#ifdef CONFIG_WIN9X
A_(OSType),
#endif
A_(OSVersion),
A_(PriorHotkey),
A_(PriorKey),
A_x(ProgramFiles, BIV_SpecialFolderPath),
A_x(Programs, BIV_SpecialFolderPath),
A_x(ProgramsCommon, BIV_SpecialFolderPath),
A_(PtrSize),
A_w(RegView),
A_(ScreenDPI),
A_x(ScreenHeight, BIV_ScreenWidth_Height),
A_x(ScreenWidth, BIV_ScreenWidth_Height),
A_(ScriptDir),
A_(ScriptFullPath),
A_(ScriptHwnd),
A_w(ScriptName),
A_x(Sec, BIV_DateTime),
A_w(SendLevel),
A_w(SendMode),
A_x(Space, BIV_Space_Tab),
A_x(StartMenu, BIV_SpecialFolderPath),
A_x(StartMenuCommon, BIV_SpecialFolderPath),
A_x(Startup, BIV_SpecialFolderPath),
A_x(StartupCommon, BIV_SpecialFolderPath),
A_w(StoreCapslockMode),
A_w(StringCaseSense),
A_x(Tab, BIV_Space_Tab),
A_(Temp), // Debatably should be A_TempDir, but brevity seemed more popular with users, perhaps for heavy uses of the temp folder.,
A_(ThisFunc),
A_(ThisHotkey),
A_(ThisLabel),
A_(TickCount),
A_(TimeIdle),
A_x(TimeIdleKeyboard, BIV_TimeIdlePhysical),
A_x(TimeIdleMouse, BIV_TimeIdlePhysical),
A_(TimeIdlePhysical),
A_(TimeSincePriorHotkey),
A_(TimeSinceThisHotkey),
A_w(TitleMatchMode),
A_wx(TitleMatchModeSpeed, BIV_TitleMatchModeSpeed, BIV_TitleMatchMode_Set),
A_(TrayMenu),
A_x(UserName, BIV_UserName_ComputerName),
A_x(WDay, BIV_DateTime),
A_wx(WinDelay, BIV_xDelay, BIV_xDelay_Set),
A_(WinDir),
A_w(WorkingDir),
A_x(YDay, BIV_DateTime),
A_x(Year, BIV_DateTime),
A_x(YWeek, BIV_DateTime),
A_x(YYYY, BIV_DateTime)
};
#undef A_
#undef A_x
#undef A_w
#undef A_wx
#undef VF
// See Script::CreateWindows() for details about the following:
typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND);
static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType)
GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener");
static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType)
GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener");
// General note about the methods in here:
// Want to be able to support multiple simultaneous points of execution
// because more than one subroutine can be executing simultaneously
// (well, more precisely, there can be more than one script subroutine
// that's in a "currently running" state, even though all such subroutines,
// except for the most recent one, are suspended. So keep this in mind when
// using things such as static data members or static local variables.
Script::Script()
: mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL)
, mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0)
, mEndChar(0), mThisHotkeyModifiersLR(0)
, mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mExitReason(EXIT_NONE)
, mFirstLabel(NULL), mLastLabel(NULL)
, mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0)
, mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0)
, mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0)
, mOpenBlock(NULL), mNextLineIsFunctionBody(false), mNoUpdateLabels(false)
, mClassObjectCount(0), mUnresolvedClasses(NULL), mClassProperty(NULL), mClassPropertyDef(NULL)
, mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true)
, mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T(""))
, mScriptName(NULL)
, mIsReadyToExecute(false), mAutoExecSectionIsRunning(false)
, mIsRestart(false), mErrorStdOut(false)
#ifndef AUTOHOTKEYSC
, mIncludeLibraryFunctionsThenExit(NULL)
#endif
, mUninterruptedLineCountMax(1000), mUninterruptibleTime(17)
, mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically.
, mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use.
, mCustomIconNumber(0)
{
// v1.0.25: mLastScriptRest (removed in v2) and mLastPeekTime are now initialized
// right before the auto-exec section of the script is launched, which avoids an
// initial Sleep(10) in ExecUntil that would otherwise occur.
ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe.
mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed.
// Lastly (after the above have been initialized), anything that can fail:
if ( !(mTrayMenu = AddMenu(MENU_TYPE_POPUP)) ) // realistically never happens
{
ScriptError(_T("No tray mem"));
ExitApp(EXIT_CRITICAL);
}
else
mTrayMenu->AppendStandardItems();
#ifdef _DEBUG
if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check.
ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST)."));
if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3)
ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST)."));
if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode.
ScriptError(_T("DEBUG: g_act and enum_act are out of sync."));
int LargestMaxParams, i, j;
ActionTypeType *np;
// Find the Largest value of MaxParams used by any command and make sure it
// isn't something larger than expected by the parsing routines:
for (LargestMaxParams = i = 0; i < g_ActionCount; ++i)
{
if (g_act[i].MaxParams > LargestMaxParams)
LargestMaxParams = g_act[i].MaxParams;
// This next part has been tested and it does work, but only if one of the arrays
// contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated.
// Relies on short-circuit boolean order:
for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np);
if (j >= MAX_NUMERIC_PARAMS)
{
ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.")
_T(" This would result in reading beyond the bounds of the array."));
return;
}
}
if (LargestMaxParams > MAX_ARGS)
ScriptError(_T("DEBUG: At least one command supports more arguments than allowed."));
if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256)
ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType")
_T(" typedef must be changed."));
// Ensure binary-search arrays are sorted correctly:
for (int i = 1; i < _countof(g_BIF); ++i)
if (_tcsicmp(g_BIF[i-1].mName, g_BIF[i].mName) >= 0)
ScriptError(_T("DEBUG: g_BIF out of order."), g_BIF[i].mName);
for (int i = 1; i < _countof(g_BIV); ++i)
if (_tcsicmp(g_BIV[i-1].name, g_BIV[i].name) >= 0)
ScriptError(_T("DEBUG: g_BIV out of order."), g_BIV[i].name);
for (int i = 1; i < _countof(g_BIV_A); ++i)
if (_tcsicmp(g_BIV_A[i-1].name, g_BIV_A[i].name) >= 0)
ScriptError(_T("DEBUG: g_BIV_A out of order."), g_BIV_A[i].name);
#endif
OleInitialize(NULL);
}
Script::~Script() // Destructor.
{
// MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free
// system resources associated with the hook."
AddRemoveHooks(0); // Remove all hooks.
if (mNIC.hWnd) // Tray icon is installed.
Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it.
int i;
// It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars).
// This is because one GUI window might get destroyed and take with it a menu bar that is still
// in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching
// its menu bar prior to destroying its window.
GuiType* gui;
while (gui = g_firstGui) // Destroy any remaining GUI windows (due to e.g. circular references). Also: assignment.
gui->Destroy();
for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts.
if (GuiType::sFont[i].hfont)
DeleteObject(GuiType::sFont[i].hfont);
// The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc.
// But that should be harmless:
// MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject."
// Above: Probably best to have removed icon from tray and destroyed any Gui windows that were
// using it prior to getting rid of the script's custom icon below:
if (mCustomIcon)
{
DestroyIcon(mCustomIcon);
DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL.
}
// Since they're not associated with a window, we must free the resources for all popup menus.
// Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu
// destruction is done AFTER the GUI windows are destroyed:
for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu)
m->Dispose();
// Since tooltip windows are unowned, they should be destroyed to avoid resource leak:
for (i = 0; i < MAX_TOOLTIPS; ++i)
if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i]))
DestroyWindow(g_hWndToolTip[i]);
if (mOnClipboardChange.Count()) // Remove from viewer chain.
EnableClipboardListener(false);
// Close any open sound item to prevent hang-on-exit in certain operating systems or conditions.
// If there's any chance that a sound was played and not closed out, or that it is still playing,
// this check is done. Otherwise, the check is avoided since it might be a high overhead call,
// especially if the sound subsystem part of the OS is currently swapped out or something:
if (g_SoundWasPlayed)
{
TCHAR buf[MAX_PATH * 2];
mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL);
if (*buf) // "playing" or "stopped"
mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL);
}
#ifdef ENABLE_KEY_HISTORY_FILE
KeyHistoryToFile(); // Close the KeyHistory file if it's open.
#endif
DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety.
OleUninitialize();
}
ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart)
// Returns OK or FAIL.
// Caller has provided an empty string for aScriptFilename if this is a compiled script.
// Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet.
{
mIsRestart = aIsRestart;
TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with.
#ifdef AUTOHOTKEYSC
// Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(),
// so that when the script is started from the command line but the user didn't type the
// extension, the extension will be included. This necessary because otherwise
// #SingleInstance wouldn't be able to detect duplicate versions in every case.
// It also provides more consistency.
GetModuleFileName(NULL, buf, _countof(buf));
#else
TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 20]; // For simplicity, allow at least space for +2 (see below) and "AutoHotkey.chm".
if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme.
{
// Since no script-file was specified on the command line, use the default name.
// For portability, first check if there's an <EXENAME>.ahk file in the current directory.
LPTSTR suffix, dot;
DWORD exe_len = GetModuleFileName(NULL, exe_buf, MAX_PATH + 2);
// exe_len can be MAX_PATH+2 on Windows XP, in which case it is not null-terminated.
// MAX_PATH+1 could mean it was truncated. Any path longer than MAX_PATH would be rare.
if (exe_len > MAX_PATH)
return FAIL; // Seems the safest option for this unlikely case.
if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path.
&& (dot = _tcsrchr(suffix, '.')) ) // Find extension part of name.
// Even if the extension is somehow zero characters, more than enough space was
// reserved in exe_buf to add "ahk":
//&& dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer?
{
_tcscpy(dot, EXT_AUTOHOTKEY);
}
else // Very unlikely.
return FAIL;
aScriptFilename = exe_buf; // Use the entire path, including the exe's directory.
if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method.
{
aScriptFilename = def_buf;
VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents
if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf))
return FAIL; // Very rare, so for simplicity just abort.
_tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it).
if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF)
{
_tcscpy(suffix, _T("\\") AHK_HELP_FILE); // Replace the executable name.
if (GetFileAttributes(exe_buf) != 0xFFFFFFFF) // Avoids hh.exe showing an error message if the file doesn't exist.
{
_sntprintf(buf, _countof(buf), _T("\"ms-its:%s::/docs/Welcome.htm\""), exe_buf);
if (ActionExec(_T("hh.exe"), buf, exe_buf, false, _T("Max")))
return FAIL;
}
// Since above didn't return, the help file is missing or failed to launch,
// so continue on and let the missing script file be reported as an error.
}
}
//else since the file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.)
}
if (*aScriptFilename == '*' && !aScriptFilename[1]) // Read script from stdin.
{
g_RunStdIn = true;
buf[0] = '*';
buf[1] = '\0';
// Seems best to disable #SingleInstance for stdin scripts.
g_AllowOnlyOneInstance = SINGLE_INSTANCE_OFF;
}
else
{
// In case the script is a relative filespec (relative to current working dir):
if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files.
return FAIL; // Due to rarity, no error msg, just abort.
}
#endif
if (!g_RunStdIn)
{
// Using the correct case not only makes it look better in title bar & tray tool tip,
// it also helps with the detection of "this script already running" since otherwise
// it might not find the dupe if the same script name is launched with different
// lowercase/uppercase letters:
ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename.
}
if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit.
return FAIL; // It already displayed the error for us.
LPTSTR filename_marker;
if (filename_marker = _tcsrchr(buf, '\\'))
{
if ( !(mFileDir = SimpleHeap::Malloc(buf, filename_marker - buf)) )
return FAIL; // It already displayed the error for us.
++filename_marker;
}
else
{
// There is no slash in "*" (i.e. g_RunStdIn). The only other known cause of this
// condition is a path being too long for GetFullPathName to expand it into buf,
// in which case buf and mFileSpec are now empty, and this will cause LoadFromFile()
// to fail and the program to exit.
mFileDir = g_WorkingDirOrig;
filename_marker = buf;
}
if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) )
return FAIL; // It already displayed the error for us.
#ifdef AUTOHOTKEYSC
// Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts.
// One reason for this is to reduce backlash if evil-doers create viruses and such
// with the program. buf already contains the full path, so no change is needed.
#else
sntprintfcat(buf, _countof(buf), _T(" - %s"), T_AHK_NAME_VERSION);
#endif
if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) )
return FAIL; // It already displayed the error for us.
// It may be better to get the module name this way rather than reading it from the registry
// (though it might be more proper to parse it out of the command line args or something),
// in case the user has moved it to a folder other than the install folder, hasn't installed it,
// or has renamed the EXE file itself. Also, enclose the full filespec of the module in double
// quotes since that's how callers usually want it because ActionExec() currently needs it that way:
*buf = '"';
if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes.
{
size_t buf_length = _tcslen(buf);
buf[buf_length++] = '"';
buf[buf_length] = '\0';
if ( !(mOurEXE = SimpleHeap::Malloc(buf)) )
return FAIL; // It already displayed the error for us.
else
{
LPTSTR last_backslash = _tcsrchr(buf, '\\');
if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName().
mOurEXEDir = _T("");
*last_backslash = '\0';
if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote.
return FAIL; // It already displayed the error for us.
}
}
mFuncs.Alloc(100); // For performance. Failure is non-critical and unlikely, so ignored for code size.
return OK;
}
ResultType Script::CreateWindows()
// Returns OK or FAIL.
{
if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function.
// Register a window class for the main window:
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(wc);
wc.lpszClassName = WINDOW_CLASS_MAIN;
wc.hInstance = g_hInstance;
wc.lpfnWndProc = MainWindowProc;
// The following are left at the default of NULL/0 set higher above:
//wc.style = 0; // CS_HREDRAW | CS_VREDRAW
//wc.cbClsExtra = 0;
//wc.cbWndExtra = 0;
// Load the main icon in the two sizes needed throughout the program:
g_IconLarge = ExtractIconFromExecutable(NULL, -IDI_MAIN, 0, 0);
g_IconSmall = ExtractIconFromExecutable(NULL, -IDI_MAIN, GetSystemMetrics(SM_CXSMICON), 0);
wc.hIcon = g_IconLarge;
wc.hIconSm = g_IconSmall;
wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu";
if (!RegisterClassEx(&wc))
{
MsgBox(_T("RegClass")); // Short/generic msg since so rare.
return FAIL;
}
TCHAR class_name[64];
HWND fore_win = GetForegroundWindow();
bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name))
&& !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too.
// Note: the title below must be constructed the same was as is done by our
// WinMain() (so that we can detect whether this script is already running)
// which is why it's standardized in g_script.mMainWindowTitle.
// Create the main window. Prevent momentary disruption of Start Menu, which
// some users understandably don't like, by omitting the taskbar button temporarily.
// This is done because testing shows that minimizing the window further below, even
// though the window is hidden, would otherwise briefly show the taskbar button (or
// at least redraw the taskbar). Sometimes this isn't noticeable, but other times
// (such as when the system is under heavy load) a user reported that it is quite
// noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because
// WS_EX_NOACTIVATE is available only on 2000/XP.
if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0
, WINDOW_CLASS_MAIN
, mMainWindowTitle
, WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0.
, CW_USEDEFAULT // xpos
, CW_USEDEFAULT // ypos
, CW_USEDEFAULT // width
, CW_USEDEFAULT // height
, NULL // parent window
, NULL // Identifies a menu, or specifies a child-window identifier depending on the window style
, g_hInstance // passed into WinMain
, NULL)) ) // lpParam
{
MsgBox(_T("CreateWindow")); // Short msg since so rare.
return FAIL;
}
#ifdef AUTOHOTKEYSC
HMENU menu = GetMenu(g_hWnd);
// Disable the Edit menu item, since it does nothing for a compiled script:
EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED);
EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false.
// But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a
// command such as ListLines in it, Refresh can be validly used.
#endif
if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER
| ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space)
, 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) )
{
MsgBox(_T("CreateWindow")); // Short msg since so rare.
return FAIL;
}
// FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT).
// It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT).
// For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject().
if(g_os.IsWinNT())
{
// Use a more appealing font on NT versions of Windows.
// Windows NT to Windows XP -> Lucida Console
HDC hdc = GetDC(g_hWndEdit);
if(!g_os.IsWinVistaOrLater())
g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console"));
else // Windows Vista and later -> Consolas
g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas"));
ReleaseDC(g_hWndEdit, hdc); // In theory it must be done.
SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0);
}
// v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity,
// which removes the 32K size restriction. Testing shows that this does not increase the actual
// amount of memory used for controls containing small amounts of text. All it does is allow
// the control to allocate more memory as needed. By specifying zero, a max
// of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP.
SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0);
// Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that
// function operate in a special mode. Therefore, it seems best to get that first call out
// of the way to avoid the possibility that the first-call behavior will cause problems with
// our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow,
// to avoid any momentary visual effects on startup.
// Update: It's done a second time because the main window might now be visible if the process
// that launched ours specified that. It seems best to override the requested state because
// some calling processes might specify "maximize" or "shownormal" as generic launch method.
// The script can display it's own main window with ListLines, etc.
// MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that
// launched the application specifies startup information in the structure. In this case,
// ShowWindow uses the information specified in the STARTUPINFO structure to show the window.
// On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT
// to use the startup information provided by the program that launched the application."
ShowWindow(g_hWnd, SW_HIDE);
ShowWindow(g_hWnd, SW_HIDE);
// Now that the first call to ShowWindow() is out of the way, minimize the main window so that
// if the script is launched from the Start Menu (and perhaps other places such as the
// Quick-launch toolbar), the window that was active before the Start Menu was displayed will
// become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent
// the launch of a script from knocking the user out of a full-screen game or other application
// that would be disrupted by an SW_MINIMIZE:
if (do_minimize)
{
ShowWindow(g_hWnd, SW_MINIMIZE);
SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button.
}
// Note: When the window is not minimized, task manager reports that a simple script (such as
// one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if
// it were immediately minimized. That is probably just due to the vagaries of how the OS
// manages windows and memory and probably doesn't actually impact system performance to the
// degree indicated. In other words, it's hard to imagine that the failure to do
// ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects
// discussed further above) significantly increases the actual memory load on the system.
g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
if (g_NoTrayIcon)
mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed.
else
// Even if the below fails, don't return FAIL in case the user is using a different shell
// or something. In other words, it is expected to fail under certain circumstances and
// we want to tolerate that:
CreateTrayIcon();
return OK;
}
void Script::EnableClipboardListener(bool aEnable)
{
static bool sEnabled = false;
if (aEnable == sEnabled) // Simplifies BIF_On.
return;
if (aEnable)
{
if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe.
// The old clipboard viewer chain method is prone to break when some other application uses
// it incorrectly. This newer method should be more reliable, but requires Vista or later:
MyAddClipboardListener(g_hWnd);
else
mNextClipboardViewer = SetClipboardViewer(g_hWnd);
}
else
{
if (MyRemoveClipboardListener && MyAddClipboardListener)
MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used.
else
ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used.
}
sEnabled = aEnable;
}
#ifdef AUTOHOTKEYSC
void Script::AllowMainWindow(bool aAllow)
{
if (g_AllowMainWindow == aAllow)
return;
g_AllowMainWindow = aAllow;
EnableOrDisableViewMenuItems(GetMenu(g_hWnd)
, aAllow ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
mTrayMenu->EnableStandardOpenItem(aAllow);
}
void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags)
{
EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags);
EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags);
EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags);
EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags);
}
#endif
void Script::CreateTrayIcon()
// It is the caller's responsibility to ensure that the previous icon is first freed/destroyed
// before calling us to install a new one. However, that is probably not needed if the Explorer
// crashed, since the memory used by the tray icon was probably destroyed along with it.
{
ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe.
// Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe.
// MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA
// with earlier Shell32.dll versions, although without the version 6.0 enhancements."
// Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA)
// for compatibility with VC++ 6.x. This is also what AutoIt3 uses:
mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE
mNIC.hWnd = g_hWnd;
mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details.
mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON;
mNIC.uCallbackMessage = AHK_NOTIFYICON;
mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : g_IconSmall;
UPDATE_TIP_FIELD
// If we were called due to an Explorer crash, I don't think it's necessary to call
// Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed
// along with Explorer. So just add it unconditionally:
if (!Shell_NotifyIcon(NIM_ADD, &mNIC))
mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed.
}
void Script::UpdateTrayIcon(bool aForceUpdate)
{