/
script_gui.cpp
10930 lines (10161 loc) · 545 KB
/
script_gui.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 "application.h" // for MsgSleep()
#include "window.h" // for SetForegroundWindowEx()
#include "qmath.h" // for qmathLog()
GuiType *Script::ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName, size_t *aNameLength, LPTSTR aControlID)
{
LPTSTR name_marker = NULL;
size_t name_length = 0;
Line::ConvertGuiName(aBuf, aCommand, &name_marker, &name_length);
if (!name_marker) // i.e. no name was specified.
{
// v1.1.20: Support omitting the GUI name when specifying a control by HWND.
if (aControlID && IsPureNumeric(aControlID, TRUE, FALSE) == PURE_INTEGER)
{
HWND control_hwnd = (HWND)ATOU64(aControlID);
if (GuiType *pgui = GuiType::FindGuiParent(control_hwnd))
return pgui;
}
if (g->GuiDefaultWindowValid())
return g->GuiDefaultWindow;
else if (g->GuiDefaultWindow) // i.e. it contains a Gui name but no valid Gui.
name_marker = g->GuiDefaultWindow->mName;
else
name_marker = _T("1"); // For backward-compatibility.
// Return the default Gui name to our caller in case it wants to create a Gui.
if (aName)
*aName = name_marker; // Caller must copy the name before releasing g->GuiDefaultWindow.
if (aNameLength)
*aNameLength = _tcslen(name_marker);
// GuiDefaultWindowValid() has already searched and determined the Gui does not exist.
return NULL;
}
// Set defaults: indicate this name can't be used to create a new Gui.
if (aName)
*aName = NULL;
if (aNameLength)
*aNameLength = 0;
if (!name_length || name_length > MAX_VAR_NAME_LENGTH)
return NULL; // Invalid name.
// Make a temporary null-terminated copy of the name for use below.
TCHAR name[MAX_VAR_NAME_LENGTH + 1];
tmemcpy(name, name_marker, name_length);
name[name_length] = '\0';
if (IsPureNumeric(name, TRUE, FALSE) == PURE_INTEGER) // Allow negatives, for flexibility.
{
unsigned __int64 gui_num = ATOU64(name); // Must use ATOU64 because ATOI64 can't handle values larger than _I64_MAX.
if (gui_num < 1 || gui_num > 99 // The range of valid Gui numbers prior to v1.1.03.
|| name_length > 2) // Length is also checked because that's how it used to be.
{
// *aName is left as NULL in this case to prevent a new Gui from being created
// with this number as its name if below fails to find a Gui. Otherwise, it
// might be possible for that Gui's name to conflict with a future Gui's HWND.
return GuiType::FindGui((HWND)gui_num);
}
// Otherwise, it's a number between 1 and 99 which is composed of no more than two
// characters; i.e. it must be treated as a name for backward compatibility reasons.
// ConvertGuiName() already stripped the leading 0 out of something like "01", for
// backward-compatibility.
}
// Search for the Gui!
GuiType *found_gui = GuiType::FindGui(name);
// If no Gui with this name exists and aName is not NULL, our caller wants to know what
// name to give a new Gui. Before returning the name, ensure it is valid. At the very
// least, space must be outlawed for Gui label names and +OwnerGUINAME. Requiring the
// name to be valid as a variable name allows for possible future use of the Gui name
// as part of a variable or function name.
if (aName)
{
// found_gui: *aName must be set for GUI_CMD_NEW even if a GUI was found, since
// found_gui will be destroyed (along with found_gui->mName) and recreated. If a
// GUI was found, obviously the name is valid and ValidateName() can be skipped.
if (found_gui || Var::ValidateName(name, false))
{
// This name is okay.
*aName = name_marker;
if (aNameLength)
*aNameLength = name_length;
}
// Otherwise, leave it set to NULL so our caller knows it is invalid.
}
return found_gui;
}
GuiType *GuiType::FindGui(LPTSTR aName)
{
for (int i = 0; i < g_guiCount; ++i)
if (!_tcsicmp(g_gui[i]->mName, aName))
return g_gui[i];
return NULL;
}
GuiType *GuiType::FindGui(HWND aHwnd)
{
// The loop will usually find it on the first iteration since
// the #1 window is default and thus most commonly used.
for (int i = 0; i < g_guiCount; ++i)
if (g_gui[i]->mHwnd == aHwnd)
return g_gui[i];
return NULL;
}
GuiType *GuiType::FindGuiParent(HWND aHwnd)
// Returns the GuiType of aHwnd or its closest ancestor which is a Gui.
{
for ( ; aHwnd; aHwnd = GetParent(aHwnd))
{
if (GuiType *gui = FindGui(aHwnd))
return gui;
if (!(GetWindowLong(aHwnd, GWL_STYLE) & WS_CHILD))
break;
}
return NULL;
}
GuiType *global_struct::GuiDefaultWindowValid()
{
if (!GuiDefaultWindow)
{
// Default Gui hasn't been set yet for this thread, so find Gui 1.
if (GuiDefaultWindow = GuiType::FindGui(_T("1"))) // Assignment.
GuiDefaultWindow->AddRef();
return GuiDefaultWindow;
}
// Update GuiDefaultWindow if it has been destroyed and recreated.
return GuiType::ValidGui(GuiDefaultWindow);
}
GuiType *GuiType::ValidGui(GuiType *&aGuiRef)
{
if (aGuiRef && !aGuiRef->mHwnd) // Gui existed but has been destroyed.
{
if (!*aGuiRef->mName) // v1.1.04: It was an anonymous GUI, so no point keeping it around.
{
aGuiRef->Release();
aGuiRef = NULL;
return NULL;
}
GuiType *recreated_gui;
if ( !(recreated_gui = GuiType::FindGui(aGuiRef->mName)) )
return NULL; // Gui is not valid, so return NULL.
// Gui has been recreated, so update the reference:
recreated_gui->AddRef();
aGuiRef->Release();
aGuiRef = recreated_gui;
}
// Above verified it either points to a valid Gui or is NULL.
return aGuiRef;
}
ResultType Script::PerformGui(LPTSTR aBuf, LPTSTR aParam2, LPTSTR aParam3, LPTSTR aParam4)
{
LPTSTR aCommand; // Set by ResolveGui().
LPTSTR name; // Set by ResolveGui() if it returns NULL.
size_t name_length; //
GuiType *pgui = ResolveGui(aBuf, aCommand, &name, &name_length);
if (!pgui && !name)
return ScriptError(ERR_INVALID_GUI_NAME, aBuf);
GuiCommands gui_command = Line::ConvertGuiCommand(aCommand);
if (gui_command == GUI_CMD_INVALID)
// This is caught at load-time 99% of the time and can only occur here if the sub-command name
// or Gui name is contained in a variable reference.
return ScriptError(ERR_PARAM1_INVALID, aCommand);
PRIVATIZE_S_DEREF_BUF; // See comments in GuiControl() about this.
ResultType result = OK; // Set default return value for use with all instances of "goto" further below.
// EVERYTHING below this point should use "result" and "goto return_the_result" instead of "return".
// First completely handle any sub-command that doesn't require the window to exist.
// In other words, don't auto-create the window before doing this command like we do
// for the others:
switch(gui_command)
{
case GUI_CMD_DESTROY:
if (pgui)
result = GuiType::Destroy(*pgui);
goto return_the_result;
case GUI_CMD_DEFAULT:
if (!pgui)
{
// Create a dummy structure to hold the name. For simplicity and maintainability,
// a full GuiType structure is constructed. We can't actually create the Gui yet,
// since that would prevent +Owner%N% from working and possibly break other scripts
// which rely on the old behaviour.
if ( (GuiType::sFont || (GuiType::sFont = (FontType *)malloc(sizeof(FontType) * MAX_GUI_FONTS))) ) // See similar line below for comments regarding sFont.
if (pgui = new GuiType())
{
if (pgui->mName = tmalloc(name_length + 1))
{
tmemcpy(pgui->mName, name, name_length);
pgui->mName[name_length] = '\0';
}
else
{
delete pgui;
pgui = NULL;
}
}
}
// Change the "default" member, not g->GuiWindow because that contains the original window
// responsible for launching this thread, which should not be changed because it is used to
// produce the contents of A_Gui.
if (pgui)
{
if (g->GuiDefaultWindow)
g->GuiDefaultWindow->Release();
pgui->AddRef();
g->GuiDefaultWindow = pgui;
}
else
result = ScriptError(ERR_OUTOFMEM);
goto return_the_result;
case GUI_CMD_OPTIONS:
// v1.0.43.09:
// Don't overload "+LastFound" because it would break existing scripts that rely on the window
// being created by +LastFound.
if (!_tcsicmp(aCommand, _T("+LastFoundExist")))
{
g->hWndLastUsed = pgui ? pgui->mHwnd : NULL;
goto return_the_result;
}
break;
case GUI_CMD_NEW: // v1.1.04: Gui, New.
if (_tcschr(aBuf, ':'))
{
if (pgui)
{
// Caller explicitly asked for a "new" Gui, so destroy this one:
GuiType::Destroy(*pgui);
pgui = NULL;
}
}
else
{
// In this case, caller has omitted the name and wants to create an "anonymous" Gui.
pgui = NULL; // Override pgui, which was set to the default Gui (if it exists).
name_length = 0; // Override name_length, which was set to the length of the default Gui name.
//name = _T(""); // Unnecessary since name is not expected to be null-terminated.
// Below will allocate an empty name, for simplicity and maintainability --
// this way, mName is always non-NULL and points to malloc'd memory.
}
break;
}
// If the window doesn't currently exist, don't auto-create it for those commands for
// which it wouldn't make sense. Note that things like FONT and COLOR are allowed to
// auto-create the window, since those commands can be legitimately used prior to the
// first "Gui Add" command. Also, it seems best to allow SHOW even though all it will
// do is create and display an empty window.
if (!pgui)
{
switch(gui_command)
{
case GUI_CMD_SUBMIT:
case GUI_CMD_CANCEL:
case GUI_CMD_FLASH:
case GUI_CMD_MINIMIZE:
case GUI_CMD_MAXIMIZE:
case GUI_CMD_RESTORE:
goto return_the_result; // Nothing needs to be done since the window object doesn't exist.
}
if (g_guiCount == g_guiCountMax)
{
// g_gui is full or hasn't been allocated yet, so allocate or expand it. Start at a low
// number since most scripts don't use many Gui windows, and double each time for simplicity
// and to avoid lots of intermediate reallocations if the script creates many Gui windows.
int new_max = g_guiCountMax ? g_guiCountMax * 2 : 8;
GuiType **new_gui_array = (GuiType **)realloc(g_gui, new_max * sizeof(GuiType *));
if (!new_gui_array)
{
result = FAIL; // No error displayed since extremely rare.
goto return_the_result;
}
g_gui = new_gui_array;
g_guiCountMax = new_max;
}
// Otherwise: Create the object and (later) its window, since all the other sub-commands below need it:
for (;;) // For break, to reduce repetition of cleanup-on-failure code.
{
// v1.0.44.14: sFont is created upon first use to conserve ~14 KB memory in non-GUI scripts.
// v1.1.29.00: sFont is created here rather than in FindOrCreateFont(), which is called by
// the constructor below, to avoid the need to add extra logic in several places to detect
// a failed/NULL array. Previously that was done by simply terminating the script.
if ( (GuiType::sFont || (GuiType::sFont = (FontType *)malloc(sizeof(FontType) * MAX_GUI_FONTS))) )
if (pgui = new GuiType())
{
if (pgui->mControl = (GuiControlType *)malloc(GUI_CONTROL_BLOCK_SIZE * sizeof(GuiControlType)))
{
if (pgui->mName = tmalloc(name_length + 1))
{
tmemcpy(pgui->mName, name, name_length);
pgui->mName[name_length] = '\0';
pgui->mControlCapacity = GUI_CONTROL_BLOCK_SIZE;
g_gui[g_guiCount++] = pgui;
break;
}
free(pgui->mControl);
}
delete pgui;
}
result = ScriptError(ERR_OUTOFMEM);
goto return_the_result;
}
}
GuiType &gui = *pgui; // For performance.
// Now handle any commands that should be handled prior to creation of the window in the case
// where the window doesn't already exist:
LPTSTR options;
if (gui_command == GUI_CMD_OPTIONS)
options = aCommand;
else if (gui_command == GUI_CMD_NEW)
options = aParam2;
else
options = NULL;
bool set_last_found_window = false;
ToggleValueType own_dialogs = TOGGLE_INVALID;
Var *hwnd_var = NULL;
if (options)
if (!gui.ParseOptions(options, set_last_found_window, own_dialogs, hwnd_var))
{
result = FAIL; // It already displayed the error.
goto return_the_result;
}
// Create the window if needed. Since it should not be possible for our window to get destroyed
// without our knowing about it (via the explicit handling in its window proc), it shouldn't
// be necessary to check the result of IsWindow(gui.mHwnd):
if (!gui.mHwnd && !gui.Create())
{
GuiType::Destroy(gui); // Get rid of the object so that it stays in sync with the window's existence.
result = ScriptError(_T("Could not create window."));
goto return_the_result;
}
if (gui_command == GUI_CMD_NEW) // v1.1.04: Gui, New. v1.1.08: now also applies to Gui, Name:New.
{
// The following comments are only applicable to Gui, New (anonymous Gui):
// Now that the HWND is known, we could use it as the Gui's name. However, that isn't
// done because it would allow a Gui to be created using an invalid HWND as a name
// (and that invalid HWND could become valid for some other window, later):
//
// Gui, New ; Creates a new Gui and sets it as default.
// Gui, Destroy ; Destroys the Gui but does not affect g->GuiDefaultWindow or g->DialogOwner.
// Gui, +LastFound ; This would create a Gui using the HWND of the previous one as a name.
//
// Instead, A_Gui returns the HWND when mName is an empty string.
// Make the new window the default, for convenience:
if (g->GuiDefaultWindow)
g->GuiDefaultWindow->Release();
pgui->AddRef();
g->GuiDefaultWindow = pgui;
}
if (hwnd_var) // v1.1.04: +HwndVarName option.
hwnd_var->AssignHWND(gui.mHwnd);
if (options)
{
// After creating the window, apply remaining options:
if (set_last_found_window)
g->hWndLastUsed = gui.mHwnd;
if (own_dialogs != TOGGLE_INVALID) // v1.0.35.06: Plus or minus "OwnDialogs" was present rather than being entirely absent.
{
if (g->DialogOwner)
g->DialogOwner->Release();
if (own_dialogs == TOGGLED_ON)
{
gui.AddRef();
g->DialogOwner = &gui;
}
else
g->DialogOwner = NULL; // Reset to NULL when "-OwnDialogs" is present.
}
if (gui_command == GUI_CMD_NEW && *aParam3)
SetWindowText(gui.mHwnd, aParam3);
goto return_the_result;
}
GuiControls gui_control_type = GUI_CONTROL_INVALID;
int index;
switch (gui_command)
{
case GUI_CMD_ADD:
if ( !(gui_control_type = Line::ConvertGuiControl(aParam2)) )
{
result = ScriptError(ERR_PARAM2_INVALID, aParam2);
goto return_the_result;
}
result = gui.AddControl(gui_control_type, aParam3, aParam4); // It already displayed any error.
goto return_the_result;
case GUI_CMD_MARGIN:
if (*aParam2)
gui.mMarginX = gui.Scale(ATOI(aParam2)); // Seems okay to allow negative margins.
if (*aParam3)
gui.mMarginY = gui.Scale(ATOI(aParam3)); // Seems okay to allow negative margins.
goto return_the_result;
case GUI_CMD_MENU:
UserMenu *menu;
if (*aParam2)
{
// By design, the below will give a slightly misleading error if the specified menu is the
// TRAY menu, since it should be obvious that it cannot be used as a menu bar (since it
// must always be of the popup type):
if ( !(menu = FindMenu(aParam2)) || menu == g_script.mTrayMenu ) // Relies on short-circuit boolean.
{
result = ScriptError(ERR_MENU, aParam2);
goto return_the_result;
}
menu->Create(MENU_TYPE_BAR); // Ensure the menu physically exists and is the "non-popup" type (for a menu bar).
}
else
menu = NULL;
SetMenu(gui.mHwnd, menu ? menu->mMenu : NULL); // Add or remove the menu.
if (menu) // v1.1.04: Keyboard accelerators.
gui.UpdateAccelerators(*menu);
else
gui.RemoveAccelerators();
goto return_the_result;
case GUI_CMD_SHOW:
result = gui.Show(aParam2, aParam3);
goto return_the_result;
case GUI_CMD_SUBMIT:
result = gui.Submit(_tcsicmp(aParam2, _T("NoHide")));
goto return_the_result;
case GUI_CMD_CANCEL:
result = gui.Cancel();
goto return_the_result;
case GUI_CMD_MINIMIZE:
// If the window is hidden, it is unhidden as a side-effect (this happens even for SW_SHOWMINNOACTIVE).
ShowWindow(gui.mHwnd, SW_MINIMIZE);
goto return_the_result;
case GUI_CMD_MAXIMIZE:
ShowWindow(gui.mHwnd, SW_MAXIMIZE); // If the window is hidden, it is unhidden as a side-effect.
goto return_the_result;
case GUI_CMD_RESTORE:
ShowWindow(gui.mHwnd, SW_RESTORE); // If the window is hidden, it is unhidden as a side-effect.
goto return_the_result;
case GUI_CMD_FONT:
result = gui.SetCurrentFont(aParam2, aParam3);
goto return_the_result;
case GUI_CMD_LISTVIEW:
case GUI_CMD_TREEVIEW:
if (*aParam2)
{
GuiIndexType control_index = gui.FindControl(aParam2); // Search on either the control's variable name or its ClassNN.
if (control_index < gui.mControlCount)
{
GuiControlType &control = gui.mControl[control_index]; // For maintainability, and might slightly reduce code size.
if (gui_command == GUI_CMD_LISTVIEW)
{
if (control.type == GUI_CONTROL_LISTVIEW) // v1.0.46.09: Must validate that it's the right type of control; otherwise some LV_* functions can crash due to the control not having malloc'd the special ListView struct that tracks column attributes.
gui.mCurrentListView = &control;
//else mismatched control type, so just leave it unchanged.
}
else // GUI_CMD_TREEVIEW
{
if (control.type == GUI_CONTROL_TREEVIEW)
gui.mCurrentTreeView = &control;
//else mismatched control type, so just leave it unchanged.
}
}
//else it seems best never to change it to be "no control" since it doesn't seem to have much use.
}
goto return_the_result;
case GUI_CMD_TAB:
{
if (*aParam3 // Which tab control. Must be processed prior to Param2 since it might change mCurrentTabControlIndex.
|| !*aParam2) // Both the tab control number and the tab number were omitted.
{
if (*aParam3)
{
index = ATOI(aParam3) - 1;
if (index < 0 || index > MAX_TAB_CONTROLS - 1)
{
result = ScriptError(ERR_PARAM3_INVALID, aParam3);
goto return_the_result;
}
}
else
index = MAX_TAB_CONTROLS; // i.e. "no tab"
if (gui.mCurrentTabControlIndex != index) // This is checked early in case of early return in the next section due to error.
{
if (GuiControlType *tab_control = gui.FindTabControl(gui.mCurrentTabControlIndex))
{
// Autosize the previous tab control. Has no effect if it is not a Tab3 control or has
// already been autosized. Doing it at this point allows the script to set different
// margins for inside and outside the tab control, and is simpler than the alternative:
// waiting until the next external control is added. The main drawback is that the
// script is unable to alternate between tab controls and still utilize autosizing.
// On the flip side, scripts can use this to their advantage -- to add controls which
// should not affect the tab control's size.
gui.AutoSizeTabControl(*tab_control);
}
gui.mCurrentTabControlIndex = index;
// Fix for v1.1.23.00: This section was restructured so that the following is done even
// if both parameters are omitted (fixes the "none at all" condition mentioned below).
// Fix for v1.0.38.02: Changing to a different tab control (or none at all when there
// was one before, or vice versa) should start a new radio group:
gui.mInRadioGroup = false;
}
}
if (*aParam2) // Index or name of a particular tab inside a control.
{
if (!*aParam3 && gui.mCurrentTabControlIndex == MAX_TAB_CONTROLS)
// Provide a default: the most recently added tab control. If there are no
// tab controls, assume the index is the first tab control (i.e. a tab control
// to be created in the future). Fix for v1.0.46.16: This section must be done
// prior to gui.FindTabControl() below because otherwise, a script that does
// "Gui Tab" will find that a later use of "Gui Tab, TabName" won't work unless
// the third parameter (which tab control) is explicitly specified.
gui.mCurrentTabControlIndex = gui.mTabControlCount ? gui.mTabControlCount - 1 : 0;
bool exact_match = !_tcsicmp(aParam4, _T("Exact")); // v1.0.37.03.
// Unlike "GuiControl, Choose", in this case, don't allow negatives since that would just
// generate an error msg further below:
if (!exact_match && IsPureNumeric(aParam2, false, false))
{
index = ATOI(aParam2) - 1;
if (index < 0 || index > MAX_TABS_PER_CONTROL - 1)
{
result = ScriptError(ERR_PARAM2_INVALID, aParam2);
goto return_the_result;
}
}
else
{
index = -1; // Set default to be "failure".
GuiControlType *tab_control = gui.FindTabControl(gui.mCurrentTabControlIndex);
if (tab_control)
index = gui.FindTabIndexByName(*tab_control, aParam2, exact_match); // Returns -1 on failure.
if (index == -1)
{
result = ScriptError(_T("Tab name doesn't exist yet."), aParam2);
goto return_the_result;
}
}
if (gui.mCurrentTabIndex != index)
{
gui.mCurrentTabIndex = index;
gui.mInRadioGroup = false; // A fix for v1.0.38.02, see comments at similar line above.
}
}
goto return_the_result;
}
case GUI_CMD_COLOR:
// AssignColor() takes care of deleting old brush, etc.
// In this case, a blank for either param means "leaving existing color alone", in which
// case AssignColor() is not called since it would assume CLR_NONE then.
if (*aParam2)
AssignColor(aParam2, gui.mBackgroundColorWin, gui.mBackgroundBrushWin);
if (*aParam3)
{
AssignColor(aParam3, gui.mBackgroundColorCtl, gui.mBackgroundBrushCtl);
// As documented, the following is not done. Primary reasons:
// 1) Allows any custom color that was explicitly specified via "Gui, Add, ListView, BackgroundGreen"
// to stay in effect rather than being overridden by this change. You could argue that this
// could be detected by asking the control its background color and if it matches the previous
// mBackgroundColorCtl (which might be CLR_DEFAULT?), it's 99% likely it was not an
// individual/explicit custom color and thus should be changed here. But that would be even
// more complexity so it seems better to keep it simple.
// 2) Reduce code size.
//for (GuiIndexType u = 0; u < gui.mControlCount; ++u)
// if (gui.mControl[u].type == GUI_CONTROL_LISTVIEW && ListView_GetTextBkColor(..) != prev_bk_color_ctl)
// {
// ListView_SetTextBkColor(gui.mControl[u].hwnd, gui.mBackgroundColorCtl);
// ListView_SetBkColor(gui.mControl[u].hwnd, gui.mBackgroundColorCtl);
// }
// ... and probably similar for TREEVIEW.
}
if (IsWindowVisible(gui.mHwnd))
// Force the window to repaint so that colors take effect immediately.
// UpdateWindow() isn't enough sometimes/always, so do something more aggressive:
InvalidateRect(gui.mHwnd, NULL, TRUE);
goto return_the_result;
case GUI_CMD_FLASH:
// Note that FlashWindowEx() could enable parameters for flashing the window a given number of times
// and at a certain frequency, and other options such as only-taskbar-button or only-caption.
// Set FlashWindowEx() for more ideas:
FlashWindow(gui.mHwnd, _tcsicmp(aParam2, _T("Off")) ? TRUE : FALSE);
goto return_the_result;
} // switch()
result = FAIL; // Should never be reached, but avoids compiler warning and improves bug detection.
return_the_result:
DEPRIVATIZE_S_DEREF_BUF;
return result;
}
ResultType Line::GuiControl(LPTSTR aCommand, LPTSTR aControlID, LPTSTR aParam3, Var *aParam3Var)
{
GuiType *pgui = Script::ResolveGui(aCommand, aCommand, NULL, 0, aControlID);
GuiControlCmds guicontrol_cmd = Line::ConvertGuiControlCmd(aCommand);
if (guicontrol_cmd == GUICONTROL_CMD_INVALID)
// This is caught at load-time 99% of the time and can only occur here if the sub-command name
// or Gui name is contained in a variable reference. Since it's so rare, the handling of it is
// debatable, but to keep it simple just set ErrorLevel:
return SetErrorLevelOrThrow();
if (!pgui)
// This departs from the tradition used by PerformGui() but since this type of error is rare,
// and since use ErrorLevel adds a little bit of flexibility (since the script's current thread
// is not unconditionally aborted), this seems best:
return SetErrorLevelOrThrow();
GuiType &gui = *pgui; // For performance.
GuiIndexType control_index = gui.FindControl(aControlID);
if (control_index >= gui.mControlCount) // Not found.
return SetErrorLevelOrThrow();
GuiControlType &control = gui.mControl[control_index]; // For performance and convenience.
// Beyond this point, errors are rare so set the default to "no error":
g_ErrorLevel->Assign(ERRORLEVEL_NONE);
// Fixed for v1.0.48.04: Some operations on a GUI control can trigger a callback or OnMessage function;
// e.g. SendMessage(control.hwnd, STM_SETIMAGE, ...). Such a function is then likely to change the contents
// of the deref buffer, which would then alter the contents of the parameters used by commands like
// GuiControl. To prevent that, make the current deref buffer private until this function returns. That
// forces any newly launched callback or OnMessage function to create a new deref buffer if it needs one.
// The main alternative to this method is to make copies of all the parameters and point the parameters to
// the copies. But since the parameters might be very large, that method could perform much worse and would
// be more complicated, especially since 99.9% of the time, the copies would turn out to be unnecessary
// because the action doesn't wind up triggering any callback or OnMessage function.
PRIVATIZE_S_DEREF_BUF;
ResultType result = OK; // Set default return value for use with all instances of "goto" further below.
// EVERYTHING below this point should use "result" and "goto return_the_result" instead of "return".
LPTSTR malloc_buf;
RECT rect;
WPARAM checked;
GuiControlType *tab_control;
int new_pos;
SYSTEMTIME st[2];
int selection_index;
bool do_redraw_if_in_tab = false;
bool do_redraw_unconditionally = false;
switch (guicontrol_cmd)
{
case GUICONTROL_CMD_OPTIONS:
{
GuiControlOptionsType go; // Its contents not currently used here, but it might be in the future.
gui.ControlInitOptions(go, control);
result = gui.ControlParseOptions(aCommand, go, control, control_index, aParam3Var);
goto return_the_result;
}
case GUICONTROL_CMD_CONTENTS:
case GUICONTROL_CMD_TEXT:
switch (control.type)
{
case GUI_CONTROL_TEXT:
case GUI_CONTROL_LINK:
case GUI_CONTROL_GROUPBOX:
do_redraw_unconditionally = (control.attrib & GUI_CONTROL_ATTRIB_BACKGROUND_TRANS); // v1.0.40.01.
// Note that it isn't sufficient in this case to do InvalidateRect(control.hwnd, ...).
break;
case GUI_CONTROL_PIC:
{
// Update: The below doesn't work, so it will be documented that a picture control
// should be always be referred to by its original filename even if the picture changes.
// Set the text unconditionally even if the picture can't be loaded. This text must
// be set to allow GuiControl(Get) to be able to operate upon the picture without
// needing to identify it via something like "Static14".
//SetWindowText(control.hwnd, aParam3);
//SendMessage(control.hwnd, WM_SETTEXT, 0, (LPARAM)aParam3);
// Set default options, to be possibly overridden by any options actually present:
// Fixed for v1.0.23: Below should use GetClientRect() vs. GetWindowRect(), otherwise
// a size too large will be returned if the control has a border:
GetClientRect(control.hwnd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
int icon_number = 0; // Zero means "load icon or bitmap (doesn't matter)".
// Note that setting the control's picture handle to NULL sometimes or always shrinks
// the control down to zero dimensions, so must be done only after the above.
// Parse any options that are present in front of the filename:
LPTSTR next_option = omit_leading_whitespace(aParam3);
if (*next_option == '*') // Options are present. Must check this here and in the for-loop to avoid omitting legitimate whitespace in a filename that starts with spaces.
{
LPTSTR option_end;
TCHAR orig_char;
for (; *next_option == '*'; next_option = omit_leading_whitespace(option_end))
{
// Find the end of this option item:
if ( !(option_end = StrChrAny(next_option, _T(" \t"))) ) // Space or tab.
option_end = next_option + _tcslen(next_option); // Set to position of zero terminator instead.
// Permanently terminate in between options to help eliminate ambiguity for words contained
// inside other words, and increase confidence in decimal and hexadecimal conversion.
orig_char = *option_end;
*option_end = '\0';
++next_option; // Skip over the asterisk. It might point to a zero terminator now.
if (!_tcsnicmp(next_option, _T("Icon"), 4))
icon_number = ATOI(next_option + 4); // LoadPicture() correctly handles any negative value.
else
{
switch (ctoupper(*next_option))
{
case 'W':
width = ATOI(next_option + 1);
break;
case 'H':
height = ATOI(next_option + 1);
break;
// If not one of the above, such as zero terminator or a number, just ignore it.
}
}
*option_end = orig_char; // Undo the temporary termination so that loop's omit_leading() will work.
} // for() each item in option list
// The below assigns option_end + 1 vs. next_option in case the filename is contained in a
// variable ref and/ that filename contains leading spaces. Example:
// GuiControl,, MyPic, *w100 *h-1 %FilenameWithLeadingSpaces%
// Update: Windows XP and perhaps other OSes will load filenames-containing-leading-spaces
// even if those spaces are omitted. However, I'm not sure whether all API calls that
// use filenames do this, so it seems best to include those spaces whenever possible.
aParam3 = *option_end ? option_end + 1 : option_end; // Set aParam3 to the start of the image's filespec.
}
//else options are not present, so do not set aParam3 to be next_option because that would
// omit legitimate spaces and tabs that might exist at the beginning of a real filename (file
// names can start with spaces).
// See comments in ControlLoadPicture():
if (!gui.ControlLoadPicture(control, aParam3, width, height, icon_number))
goto error;
// Fix for v1.0.33.02: If this control belongs to a tab control and is visible (i.e. its page
// in the tab control is the current page), must redraw the tab control to get the picture/icon
// to update correctly. v1.0.40.01: Pictures such as .Gif sometimes disappear (even if they're
// not in a tab control):
//do_redraw_if_in_tab = true;
do_redraw_unconditionally = true;
break; // Rather than return, continue on to do the redraw.
}
case GUI_CONTROL_BUTTON:
break;
case GUI_CONTROL_CHECKBOX:
case GUI_CONTROL_RADIO:
if (guicontrol_cmd == GUICONTROL_CMD_CONTENTS && IsPureNumeric(aParam3, true, false))
{
checked = ATOI(aParam3);
if (!checked || checked == 1 || (control.type == GUI_CONTROL_CHECKBOX && checked == -1))
{
if (checked == -1)
checked = BST_INDETERMINATE;
//else the "checked" var is already set correctly.
if (control.type == GUI_CONTROL_RADIO)
{
gui.ControlCheckRadioButton(control, control_index, checked);
goto return_the_result;
}
// Otherwise, we're operating upon a checkbox.
SendMessage(control.hwnd, BM_SETCHECK, checked, 0);
goto return_the_result;
}
//else the default SetWindowText() action will be taken below.
}
// else assume it's the text/caption for the item, so the default SetWindowText() action will be taken below.
break; // Fix for v1.0.35.01: Don't return, continue onward.
case GUI_CONTROL_LISTVIEW:
case GUI_CONTROL_TREEVIEW:
// Due to the fact that an LV's first col. can't be directly deleted and other complexities,
// this is not currently supported (also helps reduce code size). The built-in function
// for modifying columns should be used instead. Similar for TreeView.
goto return_the_result;
case GUI_CONTROL_EDIT:
case GUI_CONTROL_CUSTOM: // Make it edit the default window text
// Note that TranslateLFtoCRLF() will return the original buffer we gave it if no translation
// is needed. Otherwise, it will return a new buffer which we are responsible for freeing
// when done (or NULL if it failed to allocate the memory).
malloc_buf = (*aParam3 && (GetWindowLong(control.hwnd, GWL_STYLE) & ES_MULTILINE))
? TranslateLFtoCRLF(aParam3) : aParam3; // Automatic translation, as documented.
SetWindowText(control.hwnd, malloc_buf ? malloc_buf : aParam3); // malloc_buf is checked again in case the mem alloc failed.
if (malloc_buf && malloc_buf != aParam3)
free(malloc_buf);
goto return_the_result;
case GUI_CONTROL_DATETIME:
if (guicontrol_cmd == GUICONTROL_CMD_CONTENTS)
{
if (*aParam3)
{
if (YYYYMMDDToSystemTime(aParam3, st[0], true))
DateTime_SetSystemtime(control.hwnd, GDT_VALID, st);
//else invalid, so leave current sel. unchanged.
}
else // User wants there to be no date selection.
{
// Ensure the DTS_SHOWNONE style is present, otherwise it won't work. However,
// it appears that this style cannot be applied after the control is created, so
// this line is commented out:
//SetWindowLong(control.hwnd, GWL_STYLE, GetWindowLong(control.hwnd, GWL_STYLE) | DTS_SHOWNONE);
DateTime_SetSystemtime(control.hwnd, GDT_NONE, st); // Contents of st are ignored in this mode.
}
}
else // GUICONTROL_CMD_TEXT
{
bool use_custom_format = false; // Set default.
// Reset style to "pure" so that new style (or custom format) can take effect.
DWORD style = GetWindowLong(control.hwnd, GWL_STYLE) // DTS_SHORTDATEFORMAT==0 so can be omitted below.
& ~(DTS_LONGDATEFORMAT | DTS_SHORTDATECENTURYFORMAT | DTS_TIMEFORMAT);
if (*aParam3)
{
// DTS_SHORTDATEFORMAT and DTS_SHORTDATECENTURYFORMAT
// seem to produce identical results (both display 4-digit year), at least on XP. Perhaps
// DTS_SHORTDATECENTURYFORMAT is obsolete. In any case, it's uncommon so for simplicity, is
// not a named style. It can always be applied numerically if desired. Update:
// DTS_SHORTDATECENTURYFORMAT is now applied by default upon creation, which can be overridden
// explicitly via -0x0C in the control's options.
if (!_tcsicmp(aParam3, _T("LongDate"))) // LongDate seems more readable than "Long". It also matches the keyword used by FormatTime.
style |= DTS_LONGDATEFORMAT; // Competing styles were already purged above.
else if (!_tcsicmp(aParam3, _T("Time")))
style |= DTS_TIMEFORMAT; // Competing styles were already purged above.
else // Custom format.
use_custom_format = true;
}
//else aText is blank and use_custom_format==false, which will put DTS_SHORTDATEFORMAT into effect.
if (!use_custom_format)
SetWindowLong(control.hwnd, GWL_STYLE, style);
//else leave style unchanged so that if format is later removed, the underlying named style will
// not have been altered.
// This both adds and removes the custom format depending on aParma3:
DateTime_SetFormat(control.hwnd, use_custom_format ? aParam3 : NULL); // NULL removes any custom format so that the underlying style format is revealed.
}
goto return_the_result;
case GUI_CONTROL_MONTHCAL:
if (*aParam3)
{
DWORD gdtr = YYYYMMDDToSystemTime2(aParam3, st);
if (!gdtr) // Neither min nor max is present (or both are invalid).
break; // Leave current sel. unchanged.
if (GetWindowLong(control.hwnd, GWL_STYLE) & MCS_MULTISELECT) // Must use range-selection even if selection is only one date.
{
if (gdtr == GDTR_MIN) // No maximum is present, so set maximum to minimum.
st[1] = st[0];
//else just max, or both are present. Assume both for code simplicity.
MonthCal_SetSelRange(control.hwnd, st);
}
else
MonthCal_SetCurSel(control.hwnd, st);
//else invalid, so leave current sel. unchanged.
do_redraw_if_in_tab = true; // Confirmed necessary.
break;
}
//else blank, so do nothing (control does not support having "no selection").
goto return_the_result; // Don't break since don't the other actions below to be taken.
case GUI_CONTROL_HOTKEY:
SendMessage(control.hwnd, HKM_SETHOTKEY, gui.TextToHotkey(aParam3), 0); // This will set it to "None" if aParam3 is blank.
goto return_the_result; // Don't break since don't the other actions below to be taken.
case GUI_CONTROL_UPDOWN:
if (*aParam3 == '+') // Apply as delta from its current position.
{
new_pos = ATOI(aParam3 + 1);
// Any out of range or non-numeric value in the buddy is ignored since error reporting is
// left up to the script, which can compare contents of buddy to those of UpDown to check
// validity if it wants.
if (control.attrib & GUI_CONTROL_ATTRIB_ALTBEHAVIOR) // It has a 32-bit vs. 16-bit range.
new_pos += (int)SendMessage(control.hwnd, UDM_GETPOS32, 0, 0);
else // 16-bit. Must cast to short to omit the error portion (see comment above).
new_pos += (short)SendMessage(control.hwnd, UDM_GETPOS, 0, 0);
// Above uses +1 to omit the plus sign, which allows a negative delta via +-5.
// -5 is not treated as a delta because that would be ambiguous with an absolute position.
// In any case, it seems like too much code to be justified.
}
else
new_pos = ATOI(aParam3);
// MSDN: "If the parameter is outside the control's specified range, nPos will be set to the nearest
// valid value."
SendMessage(control.hwnd, (control.attrib & GUI_CONTROL_ATTRIB_ALTBEHAVIOR) ? UDM_SETPOS32 : UDM_SETPOS
, 0, new_pos); // Unnecessary to cast to short in the case of UDM_SETPOS, since it ignores the high-order word.
goto return_the_result; // Don't break since don't the other actions below to be taken.
case GUI_CONTROL_SLIDER:
// Confirmed this fact from MSDN: That the control automatically deals with out-of-range values
// by setting slider to min or max:
if (*aParam3 == '+') // Apply as delta from its current position.
{
new_pos = ATOI(aParam3 + 1);
if (control.attrib & GUI_CONTROL_ATTRIB_ALTBEHAVIOR)
new_pos = -new_pos; // Delta moves to opposite direction if control is inverted.
SendMessage(control.hwnd, TBM_SETPOS, TRUE
, SendMessage(control.hwnd, TBM_GETPOS, 0, 0) + new_pos);
// Above uses +1 to omit the plus sign, which allows a negative delta via +-5.
// -5 is not treated as a delta because that would be ambiguous with an absolute position.
// In any case, it seems like too much code to be justified.
}
else
SendMessage(control.hwnd, TBM_SETPOS, TRUE, gui.ControlInvertSliderIfNeeded(control, ATOI(aParam3)));
// Above msg has no return value.
goto return_the_result; // Don't break since don't the other actions below to be taken.
case GUI_CONTROL_PROGRESS:
// Confirmed through testing (PBM_DELTAPOS was also tested): The control automatically deals
// with out-of-range values by setting bar to min or max.
if (*aParam3 == '+')
// This allows a negative delta, e.g. via +-5. Nothing fancier is done since the need
// to go backwards in a progress bar is rare.
SendMessage(control.hwnd, PBM_DELTAPOS, ATOI(aParam3 + 1), 0);
else
SendMessage(control.hwnd, PBM_SETPOS, ATOI(aParam3), 0);
goto return_the_result; // Don't break since don't the other actions below to be taken.
case GUI_CONTROL_ACTIVEX:
// Don't do anything.
goto return_the_result;
case GUI_CONTROL_STATUSBAR:
SetWindowText(control.hwnd, aParam3);
goto return_the_result;
default: // Namely the following:
//case GUI_CONTROL_DROPDOWNLIST:
//case GUI_CONTROL_COMBOBOX:
//case GUI_CONTROL_LISTBOX:
//case GUI_CONTROL_TAB:
if (control.type == GUI_CONTROL_COMBOBOX && guicontrol_cmd == GUICONTROL_CMD_TEXT)
{
// Fix for v1.0.40.08: Must clear the current selection to avoid Submit/GuiControlGet
// retrieving it instead of the text that's about to be put into the Edit field. Note that
// whatever changes are done here should tested to work with ComboBox's AltSubmit option also.
// After the next text is added to the Edit field, upon GuiControlGet or "Gui Submit", that
// text will be checked against the drop-list to see if it matches any of the selections
// It's done at that stage rather than here because doing it there also solves the issue
// of the user manually entering a selection into the Edit field and then failing to get
// the position of the matching item when the ComboBox is set to AltSubmit mode.
SendMessage(control.hwnd, CB_SETCURSEL, -1, 0);
break; // v1.0.38: Fall through to the SetWindowText() method, which works to set combo's edit field.