-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.cpp
executable file
·2556 lines (2068 loc) · 99.1 KB
/
utility.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
#include "include.h" // Include headers and definitions
extern app App; // Access global object
// Print an error message out on the output log
void error(read r1, read r2, read r3, read r4, read r5, read r6, read r7, read r8, read r9) {
if (PROGRAM_TEST) log(make(L"error ", numerals(GetLastError()), L" ", make(r1, r2, r3, r4, r5, r6, r7, r8, r9)));
}
// Print an error message out on the output log
void error(int result, read r1, read r2, read r3, read r4, read r5, read r6, read r7, read r8, read r9) {
if (PROGRAM_TEST) log(make(L"error ", numerals(GetLastError()), L" result ", numerals(result), L" ", make(r1, r2, r3, r4, r5, r6, r7, r8, r9)));
}
// Print a message out on the output log
void log(read r1, read r2, read r3, read r4, read r5, read r6, read r7, read r8, read r9) {
if (!PROGRAM_TEST) return;
CString s = make(SayNow(), L" ", make(r1, r2, r3, r4, r5, r6, r7, r8, r9), L"\r\n");
OutputDebugString(s);
//TODO add it to the log tab
}
// Show a message to the user
void report(read r) {
if (PROGRAM_TEST) MessageBox(App.window.main, r, PROGRAM_NAME, MB_OK);
}
// Given access to a handle, close it and make it null
void CloseHandleSafely(HANDLE *handle) {
if (*handle && *handle != INVALID_HANDLE_VALUE) { // Only do something if it's not null or -1
if (!CloseHandle(*handle)) error(L"closehandle safely");
*handle = NULL; // Make it null so we don't try to close it again
}
}
// Start a new thread to execute the given function
void BeginThread(LPVOID function) {
// Create a new thread that runs the function
DWORD info = 0;
HANDLE thread = (HANDLE)_beginthreadex(
(void *) NULL, // Use default security attributes
(unsigned) 0, // Default initial stack size
(unsigned (__stdcall *) (void *)) function, // Function where the new thread will begin execution
(void *) NULL, // Pass no parameter to the thread
(unsigned) 0, // Create and start thread
(unsigned *) &info); // Writes thread identifier, cannot be null for Windows 95
if (!thread) error(L"beginthreadex");
// Tell the system this thread is done with the new thread handle
if (!CloseHandle(thread)) error(L"closehandle thread");
}
// Takes a dialog handle, a control identifier, and text
// Sets the text to the control
void TextDialogSet(HWND dialog, int control, read r) {
// Get a handle to the window of the control and set the text of that window
if (!SetDlgItemText(dialog, control, r)) error(L"setdlgitemtext");
}
// Takes a dialog handle and a dialog control identifier number
// Gets the text of the control
// Returns a string, blank if no text or any error
CString TextDialog(HWND dialog, int control) {
// Get a handle to the window of the control and return the text of that window
return TextWindow(GetDlgItem(dialog, control));
}
// Takes a window and text
// Sets the text to the window
void TextWindowSet(HWND window, read r) {
// Set the text to the window
if (!SetWindowText(window, r)) error(L"setwindowtext");
}
// Takes a window handle
// Get the text of the window, like its title or the text inside it
// Returns blank if no text or any error
CString TextWindow(HWND window) {
// If the window handle is null, return blank
if (!window) return L"";
// Find the required buffer size, in characters
int size =
(int)SendMessage(window, WM_GETTEXTLENGTH, 0, 0) // The number of text characters
+ 1; // Add 1 to have space in the buffer for the null terminator
// Open a string
CString s;
WCHAR *buffer = s.GetBuffer(size);
// Write the window text into the buffer
GetWindowText( // Writes all the text and a null terminator
window, // Handle to window
buffer, // Destination buffer
size); // Size of the buffer
// Close the string and return it
s.ReleaseBuffer();
return s;
}
// Add text in a new line at the bottom of an edit control, and scroll to view it
void EditAppend(HWND window, read r) {
// Add the given text to a new line at the bottom
CString s = TextWindow(window); // Get the text that's already there, the user may have edited it
if (is(s)) s += L"\r\n"; // If not blank, start with a newline to make sure r will be on its own line
s += r; // Add the given text
TextWindowSet(window, s); // Put the edited text back into the control
// Scroll down to the bottom
EditScroll(window);
}
// Scroll to the bottom of an edit control
void EditScroll(HWND window) {
// Find out how many lines there are, and then scroll down that many
LRESULT lines = SendMessage(window, EM_GETLINECOUNT, 0, 0);
SendMessage(window, EM_LINESCROLL, 0, lines);
}
// Make a list view control window
HWND WindowCreateList() {
// Create the list view window
DWORD style =
WS_CHILD | // Required for child windows
LVS_REPORT | // Details view with multiple columns
LBS_EXTENDEDSEL | // Allows multiple items to be selected
LVS_SHOWSELALWAYS | // Shows the selection even when the control doesn't have the focus
LBS_NOINTEGRALHEIGHT | // Allows the size to be specified exactly without snap
LVS_SHAREIMAGELISTS; // Will not delete the image list when the control is destroyed
HWND window = WindowCreate(WC_LISTVIEW, NULL, style, 0, App.window.main, (HMENU)WINDOW_LIST);
// Use the program image list
ListView_SetImageList(window, App.icon.list, LVSIL_SMALL);
// Load extended list view styles, requires common control 4.70
style =
LVS_EX_LABELTIP | // Unfold partially hidden labels in tooltips
LVS_EX_FULLROWSELECT | // When an item is selected, highlight it and all its subitems
LVS_EX_SUBITEMIMAGES | // Let subitems have icons
LVS_EX_HEADERDRAGDROP; // Let the user drag columns into a different order
ListView_SetExtendedListViewStyle(window, style);
return window;
}
// Make a tabstrip window
HWND WindowCreateTabs() {
// Create the tabs window
DWORD style = WS_CHILD; // Required for child windows
HWND window = WindowCreate(WC_TABCONTROL, NULL, style, 0, App.window.main, (HMENU)WINDOW_TABS);
SendMessage( // Have it use Tahoma, not the default system font
(HWND)window, // Send the message to this window
WM_SETFONT, // Message to send
(WPARAM)App.font.normal, // Handle to font
0); // Don't tell the control to immediately redraw itself
return window;
}
// Make a tooltip window
HWND WindowCreateTip() {
// Create the tooltip window
DWORD style =
WS_POPUP | // Popup window instead of a child window
TTS_ALWAYSTIP; // Show the tooltip even if the window is inactive
HWND window = WindowCreate(TOOLTIPS_CLASS, NULL, style, 0, App.window.main, NULL);
// Make the tooltip topmost
int result = SetWindowPos(
window, // Handle to window
HWND_TOPMOST, // Place the window above others without this setting
0, 0, 0, 0, // Retain the current position and size
SWP_NOMOVE |
SWP_NOSIZE |
SWP_NOACTIVATE); // Do not activate the window
if (!result) error(L"setwindowpos");
return window;
}
// Make a text edit window
HWND WindowCreateEdit(bool scrollbars, bool capacity) {
// Prepare the style of the edit control window
DWORD style =
WS_CHILD | // Required for child windows
ES_LEFT | // Left-align text
ES_MULTILINE; // Hold multiple lines of text
if (scrollbars) style |=
WS_VSCROLL | WS_HSCROLL | // Scroll bars
ES_AUTOHSCROLL | ES_AUTOVSCROLL; // Scroll when the user enters text
// Create the edit window
HWND window = WindowCreate(L"EDIT", NULL, style, 0, App.window.main, NULL);
// Have it use Tahoma, not the default system font
SendMessage(
(HWND)window, // Send the message to this window
WM_SETFONT, // Message to send
(WPARAM)App.font.normal, // Handle to font
0); // Don't tell the control to immediately redraw itself
// Expand its text capacity
if (capacity) SendMessage(window, EM_LIMITTEXT, 0, 0);
// Return the handle to the edit window we made
return window;
}
// Make a button
HWND WindowCreateButton(read r) {
// Prepare the style of the button window
DWORD style =
WS_CHILD | // Required for child windows
BS_PUSHBUTTON; // Have the button send the window a message when the user clicks it
// Create the edit window
HWND window = WindowCreate(L"BUTTON", NULL, style, 0, App.window.main, NULL);
// Title it
TextWindowSet(window, r);
// Have it use Tahoma, not the default system font
SendMessage(
(HWND)window, // Send the message to this window
WM_SETFONT, // Message to send
(WPARAM)App.font.normal, // Handle to font
0); // Don't tell the control to immediately redraw itself
// Return the handle to the button window we made
return window;
}
// Make a new window
HWND WindowCreate(read name, read title, DWORD style, int size, HWND parent, HMENU menu) {
// Create the window
HWND window = CreateWindow(
name, // System or registered window class name or class
title, // Text to show in the title bar, or null for no text
style, // Window style
size, size, size, size, // Window position and size
parent, // Handle to parent window
menu, // Menu handle or child window identification number
App.window.instance, // Program instance handle
NULL); // No parameter
if (!window) error(L"createwindow");
return window;
}
// Adjust the width and height of the given window by x and y
void WindowSize(HWND window, int x, int y) {
// No sizing necessary
if (!x && !y) return;
// Get the window's current size
RECT r;
if (!GetWindowRect(window, &r)) { error(L"getwindowrect"); return; }
// Adjust the size
Size size;
size.x = r.left;
size.y = r.top;
size.w = r.right - r.left + x;
size.h = r.bottom - r.top + y;
// Move the window
WindowMove(window, size, true);
}
// Move window to size, true to repaint
void WindowMove(HWND window, Size size, bool paint) {
// Position and resize the window and also optionally send it a paint message
if (!MoveWindow(window, size.x, size.y, size.w, size.h, paint)) error(L"movewindow");
}
// Make an edit window editable or read only
void WindowEdit(HWND window, boolean edit) {
// Send the window a messge to make it read only or editable
SendMessage(
(HWND)window, // Send the message to this window
EM_SETREADONLY, // Message to send
(WPARAM)!edit, // true to set read only
0); // Not used, must be 0
}
// Mix two colors in the given amounts
COLORREF ColorMix(COLORREF color1, int amount1, COLORREF color2, int amount2) {
// Extract the individual primary color values
int red1, red2, green1, green2, blue1, blue2;
red1 = GetRValue(color1);
red2 = GetRValue(color2);
green1 = GetGValue(color1);
green2 = GetGValue(color2);
blue1 = GetBValue(color1);
blue2 = GetBValue(color2);
// Mix each color value using a weighted average, rounds fractions down
int red, green, blue;
red = green = blue = 0;
if (amount1 + amount2) {
red = ((red1 * amount1) + (red2 * amount2)) / (amount1 + amount2);
green = ((green1 * amount1) + (green2 * amount2)) / (amount1 + amount2);
blue = ((blue1 * amount1) + (blue2 * amount2)) / (amount1 + amount2);
}
// Return the mixed color
return RGB(red, green, blue);
}
// Make a Brush from the given color
// Returns a Brush that must be deleted, or null on error
Brush CreateBrush(COLORREF color) {
Brush brush;
brush.color = color;
brush.brush = CreateSolidBrush(color);
if (!brush.brush) error(L"createsolidbrush");
return brush;
}
// Repaint the window right now
void PaintMessage(HWND window) {
// Choose window
if (!window) window = App.window.main;
// Mark the client area of the main window as necessary to draw
int result = InvalidateRect(
window, // Handle to window
NULL, // Invalidate the entire client area of the window
false); // false to not wipe the window with the background color
if (!result) error(L"invalidaterect");
// Call the window procedure directly with a paint message right now
// Send the window a paint message and have it process it right now
if (!UpdateWindow(window)) error(L"updatewindow");
}
// Adds the program icon to the taskbar notification area
void TaskbarIconAdd() {
if (App.cycle.taskbar) return; // Icon already there, leave
App.cycle.taskbar = App.stage.show->icon16; // Pick the icon for the current stage
// Add the taskbar notification icon
NOTIFYICONDATA info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info); // Size of this structure
info.hWnd = App.window.main; // Handle to the window that will receive messages
info.uID = TASKBAR_ICON; // Program defined identifier
info.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; // Mask for message, icon and tip
info.uCallbackMessage = MESSAGE_TASKBAR; // Program defined message identifier
info.hIcon = App.cycle.taskbar; // Icon handle
copyr(info.szTip, sizeof(info.szTip) / sizeof(WCHAR), PROGRAM_NAME); // Buffer for tooltip text
if (!Shell_NotifyIcon(NIM_ADD, &info)) error(L"shell_notifyicon nim_add");
}
// Updates the program icon in the taskbar notification area
void TaskbarIconUpdate() {
if (!App.cycle.taskbar) return; // No icon to update, leave
if (App.cycle.taskbar == App.stage.show->icon16) return; // Icon doesn't need to be updated, leave
App.cycle.taskbar = App.stage.show->icon16; // Record that we updated the icon
// Add the taskbar notification icon
NOTIFYICONDATA info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info); // Size of this structure
info.hWnd = App.window.main; // Handle to the window that will receive messages
info.uID = TASKBAR_ICON; // Program defined identifier
info.uFlags = NIF_ICON; // Mask for icon only
info.hIcon = App.cycle.taskbar; // Icon handle
if (!Shell_NotifyIcon(NIM_MODIFY, &info)) error(L"shell_notifyicon nim_modify");
}
// Removes the program icon from the taskbar notification area
void TaskbarIconRemove() {
if (!App.cycle.taskbar) return; // No icon to remove, leave
App.cycle.taskbar = NULL; // Record tha we removed the icon
// Remove the taskbar notification icon
NOTIFYICONDATA info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info); // Size of this structure
info.hWnd = App.window.main; // Handle to the window that will receive messages
info.uID = TASKBAR_ICON; // Program defined identifier
if (!Shell_NotifyIcon(NIM_DELETE, &info)) error(L"shell_notifyicon nim_delete");
}
// Takes a system cursor identifier
// Gets the shared handle to the cursor
// Returns it, or null if any error
HCURSOR LoadSharedCursor(read name) {
// Get the handle of the system cursor
HCURSOR cursor = (HCURSOR)LoadImage(
NULL, // Load from the system
name, // Cursor to load
IMAGE_CURSOR, // Image type
0, 0, // Use the width and height of the resource
LR_SHARED); // Share the system resource
if (!cursor) error(L"loadimage cursor");
return cursor;
}
// Takes the name of an icon resource and the size to load, or 0 for default
// Loads it
// Returns it, or null if any error
HICON LoadIconResource(read name, int w, int h) {
// Create the icon from the resource
HICON icon = (HICON)LoadImage(
App.window.instance, // Load from this instance
name, // Resource name
IMAGE_ICON, // Image type
w, h, // Width and height to load
LR_DEFAULTCOLOR); // Default flag does nothing
if (!icon) error(L"loadimage icon");
return icon;
}
// Sets the cursor to the given cursor if it isn't that already
void CursorSet(HCURSOR cursor) {
HCURSOR current = GetCursor(); // Find out what the cursor is now
if (cursor && current && cursor != current) { // If we have both and they're different
if (!SetCursor(cursor)) error(L"setcursor"); // Set the new given one
}
}
// Takes a menu name and loads it from resources
HMENU MenuLoad(read name) {
HMENU menus = LoadMenu(App.window.instance, name); // Load the menu resource
if (!menus) error(L"loadmenu");
return menus;
}
// Takes a menu index, like 0 for the first one
// Clips out the submenu at that index
HMENU MenuClip(HMENU menus, int index) {
HMENU menu = GetSubMenu(menus, index); // Clip off the submenu at the given index
if (!menu) error(L"getsubmenu");
return menu;
}
// Takes a menu, command, the state to set, and a bitmap image to set or null to not set one
// Sets the menu item
void MenuSet(HMENU menu, UINT command, UINT state, HBITMAP bitmap) {
MENUITEMINFO info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(MENUITEMINFO);
info.fMask = MIIM_STATE;
info.fState = state;
if (bitmap) { info.fMask = info.fMask | MIIM_BITMAP; info.hbmpItem = bitmap; } // Set menu item info
if (!SetMenuItemInfo(menu, command, false, &info)) error(L"setmenuiteminfo");
}
// Takes menus and whether the context menu is being shown from the taskbar notification icon or not
// Takes size null to put the menu at the mouse pointer, or a size in client coordinates
// Displays the context menu and waits for the user to make a choice
// Returns the menu item identifier of the choice, or 0 if the user cancelled the menu or any error
int MenuShow(HMENU menu, bool taskbar, Size *size) {
// Use the given size or mouse position
Size position;
if (size) {
position = *size;
position.Screen(); // Convert the given client size into screen coordinates
} else {
position = MouseScreen(); // Get the mouse position in screen coordinates
}
// Context menu for notification icon
if (taskbar) SetForegroundWindow(App.window.main);
// Show the context menu and hold execution here until the user chooses from the menu or cancels it
AreaPopUp();
int choice = (int)TrackPopupMenu(
menu, // Handle to the menu to display
TPM_NONOTIFY | // Return the chosen menu item without sending messages to the main window
TPM_RETURNCMD |
TPM_RIGHTBUTTON, // Let the user click on an item with the left or right button
position.x, // Desired menu position in screen coordinates
position.y,
0,
App.window.main,
NULL);
AreaPopDown();
// Context menu for notification icon
if (taskbar) PostMessage(App.window.main, WM_NULL, 0, 0);
// Return the user's choice, 0 they clicked outside the menu
return choice;
}
// Takes the size in the client area where the tool will be shown, and the text to show
// Assigns the tooltip window to this area and sets its text
void TipAdd(Size size, read r) {
// Attach the tooltip to a rectangle in the main window
TOOLINFO info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info); // Size of this structure
info.uFlags = TTF_SUBCLASS; // Have the tooltip control get messages from the tool window
info.hwnd = App.window.main; // Handle to the window that contains the tool region
info.uId = 0; // Tool identifying number
info.rect = size.Rectangle(); // Rectangle in the window of the tool
info.hinst = NULL; // Only used when text is loaded from a resource
info.lpszText = (WCHAR *)r; // Text
info.lParam = 0; // No additional value assigned to tool
if (!SendMessage(App.window.tip, TTM_ADDTOOL, 0, (LPARAM)&info)) error(L"sendmessage ttm_addtool");
}
// Have window capture the mouse if it doesn't have it already, null to use the main window
void MouseCapture(HWND window) {
if (!window) window = App.window.main; // Use the main window if the caller didn't specify one
if (GetCapture() != window) SetCapture(window); // If that window doesn't already have the mouse, capture it
}
// Have window release its capture of the mouse if it has it, null to use the main window
void MouseRelease(HWND window) {
if (!window) window = App.window.main; // Pick the main window if the caller didn't specify one
if (GetCapture() == window) ReleaseCapture(); // Only release it if window has it
}
// True if the mouse is in the client area but not over a child window control
bool MouseInside() {
// Get the mouse cursor's position in client window coordinates, and the size of the client window
Size mouse = MouseClient();
Size client = SizeClient();
// The mouse is inside if it is inside the client area and outside all the child window controls
return
client.Inside(mouse) &&
!App.area.list.Inside(mouse) &&
!App.area.tabs.Inside(mouse) &&
!App.area.info.Inside(mouse);
}
// Find the area, if any, the mouse is currently positioned over, null if none
Area *MouseOver() {
// Get the mouse cursor's position in client window coordinates
Size mouse = MouseClient();
Size client = SizeClient();
if (!client.Inside(mouse)) return NULL; // Make sure the mouse is inside the client area
// Move down each area to find the one the mouse is over
Area *a = App.area.all;
while (a) {
if (a->size.Inside(mouse)) return a; // Found it
a = a->next;
}
return NULL; // Not found, the mouse is away from them all
}
// Get the mouse position in x and y coordinates inside the given area
Size MouseArea(Area *a) {
Size s = MouseClient(); // Get the mouse position in client window coordinates
s.x -= a->size.x; // Convert to area coordinates
s.y -= a->size.y;
return s;
}
// Takes a window or null to use the main one
// Gets the mouse position in client coordinates
// Returns x and y coordinates in a size
Size MouseClient(HWND window) {
if (!window) window = App.window.main; // Choose window
Size s = MouseScreen(); // Get the mouse pointer position in screen coordinates
s.Client(window); // Convert the position to the client coordinates of the given window
return s;
}
// Gets the mouse position in screen coordinates
// Returns x and y coordinates in a size
Size MouseScreen() {
// If we have a popup window or menu open, report that the mouse is off the screen
Size s;
s.x = -1;
s.y = -1;
if (App.cycle.pop) return s;
// Get the mouse position in screen coordinates
POINT p;
if (!GetCursorPos(&p)) return s; // Will return error if Windows is locked
s.Set(p);
return s;
}
// Takes a system color index
// Gets the system brush for that color
// Returns a brush that should not be deleted, or null if any error
Brush BrushSystem(int color) {
// Get the system brush for the given color index, as well as the color itself
Brush brush;
brush.color = GetSysColor(color);
brush.brush = GetSysColorBrush(color);
if (!brush.brush) error(L"getsyscolorbrush");
return brush;
}
// Takes a color
// Creates a brush of that color
// Returns a brush that must be deleted, or null if any error
Brush BrushColor(COLORREF color) {
// Create a new brush of the given solid color
Brush brush;
brush.color = color;
brush.brush = CreateSolidBrush(color);
if (!brush.brush) error(L"createsolidbrush");
return brush;
}
// Takes two colors and amounts
// Mixes the colors in those porportions
// Returns the mixed color
COLORREF MixColors(COLORREF color1, int amount1, COLORREF color2, int amount2) {
// Extract the individual color values
int red1, red2, green1, green2, blue1, blue2;
red1 = GetRValue(color1);
red2 = GetRValue(color2);
green1 = GetGValue(color1);
green2 = GetGValue(color2);
blue1 = GetBValue(color1);
blue2 = GetBValue(color2);
// Mix each color value using a weighted average, rounds fractions down
int red, green, blue;
red = green = blue = 0;
if (amount1 + amount2) {
red = ((red1 * amount1) + (red2 * amount2)) / (amount1 + amount2);
green = ((green1 * amount1) + (green2 * amount2)) / (amount1 + amount2);
blue = ((blue1 * amount1) + (blue2 * amount2)) / (amount1 + amount2);
}
// Return the mixed color
return RGB(red, green, blue);
}
// Measure the width and height of the client area of the given window
Size SizeClient(HWND window) {
// Pick main window if none given
if (!window) window = App.window.main;
// Find the width and height of the client area
Size size;
RECT rectangle;
if (!GetClientRect(window, &rectangle)) { error(L"getclientrect"); return size; }
size.Set(rectangle);
return size;
}
// Find the size of the given window on the screen
Size SizeWindow(HWND window) {
// Pick main window if none given
if (!window) window = App.window.main;
// Find the width and height of the client area
Size size;
RECT rectangle;
if (!GetWindowRect(window, &rectangle)) { error(L"getwindowrect"); return size; }
size.Set(rectangle);
return size;
}
// Takes a device context with a font loaded inside, and text
// Determines how wide and high in pixels the text painted will be
// Returns the size width and height, or zeroes if any error
Size SizeText(Device *device, read r) {
// Get the pixel dimensions of text written in the loaded font
SIZE size;
if (!GetTextExtentPoint32(device->device, r, length(r), &size)) {
error(L"gettextextentpoint32");
size.cx = size.cy = 0;
}
// Return the size, will be all 0 for blank text
Size s(size);
return s;
}
// Takes a Device that has a font, text, and a bounding position and size
// Paints the text there
void PaintLabel(Device *device, read r, Size size) {
// Paint the text, if the background is opaque, this will cause a flicker
RECT rectangle = size.Rectangle();
if (!DrawText(device->device, r, -1, &rectangle, DT_NOPREFIX)) error(L"drawtext");
}
// Takes a device context that has a font loaded into it, text, position and bounding size, and formatting options
// Fills the size and paints the text with an ellipsis
void PaintText(Device *device, read r, Size size, bool horizontal, bool vertical, bool left, bool right, int adjust, HFONT font, Brush *color, Brush *background) {
// Prepare the device context
if (font) device->Font(font);
if (color) device->FontColor(color->color);
if (background) device->BackgroundColor(background->color);
// Find out how big the text will be when painted
Size text;
text = SizeText(device, r);
// If only a position was provided, put in the necessary size
if (size.w <= 0) size.w = text.w;
if (size.h <= 0) size.h = text.h;
// Define space once in a local variable
int space = 4;
// Add margins
Size bound = size;
if (left) bound.ShiftLeft(space);
if (right) bound.w -= space;
bound.Check();
// Make text small enough so it will fit within bound
if (text.w > bound.w) text.w = bound.w;
if (text.h > bound.h) text.h = bound.h;
// Position the text within bound
text.x = bound.x;
text.y = bound.y;
if (horizontal && text.w < bound.w) text.x += ((bound.w - text.w) / 2);
if (vertical && text.h < bound.h) text.y += ((bound.h - text.h) / 2);
// Adjust the text if doing so doesn't place it outside the bound
if (text.x + adjust >= bound.x && text.Right() + adjust <= bound.Right()) text.x += adjust;
// Fill the background, this won't make draw text's flicker worse
if (background) PaintFill(device, size, background->brush);
else PaintFill(device, size);
// Paint the text
RECT rectangle;
if (text.Is()) {
// Draw text paints background beneath the text and then text over it, creating a flicker
rectangle = text.Rectangle();
if (!DrawText(device->device, r, -1, &rectangle, DT_LEFT | DT_END_ELLIPSIS | DT_NOPREFIX | DT_SINGLELINE)) error(L"drawtext");
}
// Put back the device context
if (background) device->BackgroundColor(device->backgroundcolor);
if (color) device->FontColor(device->fontcolor);
if (font) device->Font(App.font.normal);
}
// Use the device to paint size with brush
void PaintFill(Device *device, Size size, HBRUSH brush) {
// Make sure there is a size to fill
if (!size.Is()) return;
// Choose brush
if (!brush) brush = App.brush.background.brush;
// Paint the rectangle
RECT rectangle = size.Rectangle();
FillRect(device->device, &rectangle, brush); // Will return error if Windows is locked
}
// Takes a device context, size, and brushes for the upper left and lower right corners
// Paints a 1 pixel wide border inside the size
void PaintBorder(Device *device, Size size, HBRUSH brush1, HBRUSH brush2) {
// Use the same brush for both corners
if (!brush2) brush2 = brush1;
// Paint the 4 edges of the border
Size edge;
edge = size; edge.w--; edge.h = 1; PaintFill(device, edge, brush1);
edge = size; edge.w = 1; edge.y++; edge.h -= 2; PaintFill(device, edge, brush1);
edge = size; edge.x += edge.w - 1; edge.w = 1; edge.h--; PaintFill(device, edge, brush2);
edge = size; edge.y += edge.h - 1; edge.h = 1; PaintFill(device, edge, brush2);
}
// Takes a device context, position, and icon
// Provide a background brush for flicker free drawing, or NULL for a transparent background
// Paints the icon
void PaintIcon(Device *device, Size position, HICON icon, HBRUSH background) {
int result = DrawIconEx(
device->device, // Handle to device context
position.x, position.y, // Position to paint the icon
icon, // Handle to icon to paint
0, 0, // Use the width and height of the icon resource
0, // Not an animated icon
background, // Paint into an offscreen bitmap over this brush first to not flicker on the screen
DI_IMAGE | DI_MASK); // Use the image and mask to draw alpha icons correctly
if (!result) error(L"drawiconex");
}
// Make a font based on what the system uses in menus, true to underline it
HFONT FontMenu(boolean underline) {
NONCLIENTMETRICS info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info); // Must define _WIN32_WINNT=0x0501 for sizeof(info) to return the size SPI_GETNONCLIENTMETRICS expects
int result = SystemParametersInfo(
SPI_GETNONCLIENTMETRICS, // System parameter to retrieve
sizeof(info), // Size of the structure
&info, // Structure to fill with information
0); // Not setting a system parameter
if (!result) { error(L"systemparametersinfo getnonclientmetrics"); return NULL; }
if (underline) info.lfMenuFont.lfUnderline = true; // Underline if requested
HFONT font = CreateFontIndirect(&info.lfMenuFont);
if (!font) error(L"createfontindirect systemparametersinfo");
return font;
}
// Make a font of the given face name and point size
HFONT FontName(read face, int points) {
LOGFONT info;
ZeroMemory(&info, sizeof(info));
info.lfHeight = -points; // Point size, minus sign required
info.lfWidth = 0; // Default width
info.lfEscapement = 0; // Not rotated
info.lfOrientation = 0;
info.lfWeight = FW_NORMAL; // Normal, not bold
info.lfItalic = (byte)false; // Not italic
info.lfUnderline = (byte)false; // Not underlined
info.lfStrikeOut = (byte)false; // No strikeout
info.lfCharSet = ANSI_CHARSET; // Use ANSI characters
info.lfOutPrecision = OUT_DEFAULT_PRECIS; // Default size precision
info.lfClipPrecision = CLIP_DEFAULT_PRECIS; // Default clipping behavior
info.lfQuality = DEFAULT_QUALITY; // Don't force antialiasing
info.lfPitchAndFamily = VARIABLE_PITCH | FF_DONTCARE; // Only used if the font name is unavailable
copyr(info.lfFaceName, sizeof(info.lfFaceName) / sizeof(WCHAR), face); // Font name
HFONT font = CreateFontIndirect(&info);
if (!font) error(L"createfontindirect logfont");
return font;
}
// Return the largest positive number amongst the given numbers, 0 if none
int Greatest(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
// Find the biggest positive number and return it
int i = 0;
if (i < i1) i = i1;
if (i < i2) i = i2;
if (i < i3) i = i3;
if (i < i4) i = i4;
if (i < i5) i = i5;
if (i < i6) i = i6;
if (i < i7) i = i7;
if (i < i8) i = i8;
return i;
}
// Tell the system what libraries this new process will use
void InitializeSystem() {
// Initialize the critical section we'll use for web downloads
InitializeCriticalSection(&App.web.section);
// Initialize the COM library including OLE
HRESULT result = OleInitialize(NULL);
if (result != S_OK && result != S_FALSE) error(L"oleinitialize"); // False just means already initialized
// Initialize our use of the common controls
INITCOMMONCONTROLSEX info; // Oh yeah
ZeroMemory(&info, sizeof(info));
info.dwSize = sizeof(info); // Size of this structure
info.dwICC = ICC_LISTVIEW_CLASSES | ICC_TREEVIEW_CLASSES; // Load list and tree view classes
if (!InitCommonControlsEx(&info)) error(L"initcommoncontrolsex");
}
// Takes a window handle and timer identifier
// Kills the timer
void KillTimerSafely(UINT_PTR timer, HWND window) {
if (!window) window = App.window.main; // Choose window
if (!KillTimer(window, timer)) error(L"killtimer"); // Kill the timer
}
// Takes a timer identifier and the number of milliseconds after which the timer should expire
// Sets the timer
void TimerSet(UINT_PTR timer, UINT time, HWND window) {
if (!window) window = App.window.main; // Choose window
if (!SetTimer(window, timer, time, NULL)) error(L"settimer"); // Set the timer
}
// Takes a path to a program and parameters, or a path to a document and null to double-click
// Shell executes it
void FileRun(read path, read parameters) {
// Shell execute the given text
ShellExecute(
App.window.main, // Handle to a window to get message boxes from this operation
NULL, // Default run
path, // Program file to run or document to open
parameters, // Parameters ot pass to program, null if path is to a document to open
NULL, // Use the current working directory
SW_SHOWNORMAL); // Default show
}
// Takes a dialog box resource name and procedure function
// Shows the dialog box
// Returns the result from the dialog box
int Dialog(read resource, DLGPROC procedure, LPARAM lparam) {
// Choose procedure
if (!procedure) procedure = DialogProcedure;
// Show the dialog box, sending messages to its procedure and returning here when it is closed
int result;
AreaPopUp();
if (lparam) result = (int)DialogBoxParam(App.window.instance, resource, App.window.main, procedure, lparam);
else result = (int)DialogBox(App.window.instance, resource, App.window.main, procedure);
AreaPopDown();
return result;
}
// Dialog box procedure
BOOL CALLBACK DialogProcedure(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) {
// The dialog is about to be displayed
switch (message) {
case WM_INITDIALOG:
// Let the system place the focus
return true;
break;
case WM_COMMAND:
// The user clicked OK, Cancel, Yes, or No
switch (LOWORD(wparam)) {
case IDOK:
case IDCANCEL: // Cancel or the corner X
case IDYES:
case IDNO:
// Close the dialog
EndDialog(dialog, LOWORD(wparam)); // Have DialogBox() return what button the user clicked
return true; // We processed the message
break;
}
break;
}
return false; // We didn't process the message
}
// Takes a tab control child window that holds tabs, an index number 0+ for a new tab, and text to title it
// Adds a new tab
void AddTab(HWND window, int index, read title) {
// Fill out the structure and send the message
TCITEM item;
ZeroMemory(&item, sizeof(item));
item.mask = TCIF_TEXT; // Parts set below
item.dwState = 0; // Ignored when inserting a new tab
item.dwStateMask = 0; // Ignored when inserting a new tab