forked from benbuck/rbtray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRBTray.cpp
More file actions
947 lines (839 loc) · 30.4 KB
/
Copy pathRBTray.cpp
File metadata and controls
947 lines (839 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
// ****************************************************************************
//
// RBTray
// Copyright (C) 1998-2010 Nikolay Redko, J.D. Purcell
// Copyright (C) 2015 Benbuck Nason
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// ****************************************************************************
#include <windows.h>
#include <windowsx.h>
#include <map>
#include <string>
#include <vector>
#include "RBTray.h"
#include "resource.h"
#define MAXTRAYITEMS 64
static UINT WM_TASKBAR_CREATED;
static HINSTANCE _hInstance;
static HMODULE _hLib;
static HWND _hwndHook;
static HWND _hwndItems[MAXTRAYITEMS];
static HWND _hwndForMenu;
static HWND _hwndStack[MAXTRAYITEMS];
static int _stackCount = 0;
BOOL gDebug = FALSE;
BOOL gPaused = FALSE;
// -- Language support --------------------------------------------------------
struct LanguageInfo {
LPCWSTR code;
LPCWSTR nativeName;
};
static const LanguageInfo g_languages[] = {
{ L"auto", L"__system__" },
{ L"en", L"English" },
{ L"zh-CN", L"\u4E2D\u6587" },
};
static const int g_languageCount = sizeof(g_languages) / sizeof(g_languages[0]);
static int g_currentLanguage = 0;
static std::map<std::wstring, std::wstring> g_strings;
static void SkipWhitespace(const char *& p) {
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++;
}
static bool ParseJsonStringValue(const char *& p, std::wstring & out) {
if (*p != '"') return false;
p++;
std::string utf8;
while (*p && *p != '"') {
if (*p == '\\') {
p++;
switch (*p) {
case '"': utf8 += '"'; break;
case '\\': utf8 += '\\'; break;
case '/': utf8 += '/'; break;
case 'n': utf8 += '\n'; break;
case 'r': utf8 += '\r'; break;
case 't': utf8 += '\t'; break;
case 'u': {
utf8 += '\\'; utf8 += 'u';
for (int i = 0; i < 4 && *(p + 1); i++) { p++; utf8 += *p; }
break;
}
default: utf8 += *p; break;
}
p++;
} else {
utf8 += *p;
p++;
}
}
if (*p != '"') return false;
p++;
int wideLen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.length(), NULL, 0);
if (wideLen <= 0) return false;
out.resize(wideLen);
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.length(), &out[0], wideLen);
return true;
}
static bool LoadLanguageFromJson(const char * jsonData, size_t size, std::map<std::wstring, std::wstring> & strings) {
const char * p = jsonData;
if (size >= 3 && (unsigned char)p[0] == 0xEF && (unsigned char)p[1] == 0xBB && (unsigned char)p[2] == 0xBF) {
p += 3;
}
SkipWhitespace(p);
if (*p != '{') return false;
p++;
while (*p) {
SkipWhitespace(p);
if (*p == '}') { p++; return true; }
std::wstring key;
if (!ParseJsonStringValue(p, key)) return false;
SkipWhitespace(p);
if (*p != ':') return false;
p++;
SkipWhitespace(p);
std::wstring value;
if (!ParseJsonStringValue(p, value)) return false;
strings[key] = value;
SkipWhitespace(p);
if (*p == ',') { p++; continue; }
if (*p == '}') { p++; return true; }
return false;
}
return false;
}
static void GetExeDir(wchar_t * dir, DWORD size);
static bool LoadLanguageFile(int index) {
wchar_t filePath[MAX_PATH];
GetExeDir(filePath, MAX_PATH);
wcscat_s(filePath, L"\\lang\\");
wcscat_s(filePath, g_languages[index].code);
wcscat_s(filePath, L".json");
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
DEBUG_PRINTF("%s: failed to open language file %ls\n", __FUNCTION__, filePath);
return false;
}
DWORD fileSize = GetFileSize(hFile, NULL);
if (fileSize == 0 || fileSize == INVALID_FILE_SIZE) {
CloseHandle(hFile);
return false;
}
std::vector<char> buffer(fileSize + 1);
DWORD bytesRead;
if (!ReadFile(hFile, buffer.data(), fileSize, &bytesRead, NULL)) {
CloseHandle(hFile);
return false;
}
CloseHandle(hFile);
buffer[fileSize] = '\0';
std::map<std::wstring, std::wstring> newStrings;
if (!LoadLanguageFromJson(buffer.data(), fileSize, newStrings)) {
DEBUG_PRINTF("%s: failed to parse language file %ls\n", __FUNCTION__, filePath);
return false;
}
g_strings.swap(newStrings);
return true;
}
static LPCWSTR GetStr(LPCWSTR key) {
auto it = g_strings.find(key);
if (it != g_strings.end()) {
return it->second.c_str();
}
return key;
}
static int DetectSystemLanguage() {
LANGID langId = GetUserDefaultUILanguage();
switch (PRIMARYLANGID(langId)) {
case LANG_CHINESE:
if (SUBLANGID(langId) == SUBLANG_CHINESE_SIMPLIFIED) {
for (int i = 0; i < g_languageCount; i++) {
if (!wcscmp(g_languages[i].code, L"zh-CN")) return i;
}
}
break;
}
for (int i = 0; i < g_languageCount; i++) {
if (!wcscmp(g_languages[i].code, L"en")) return i;
}
return 1;
}
static void GetExeDir(wchar_t * dir, DWORD size) {
GetModuleFileName(NULL, dir, size);
wchar_t * lastBackslash = wcsrchr(dir, L'\\');
if (lastBackslash) *lastBackslash = L'\0';
}
static int LoadLanguagePreference() {
wchar_t settingsPath[MAX_PATH];
GetExeDir(settingsPath, MAX_PATH);
wcscat_s(settingsPath, L"\\settings.json");
HANDLE hFile = CreateFile(settingsPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return DetectSystemLanguage();
}
DWORD fileSize = GetFileSize(hFile, NULL);
if (fileSize == 0 || fileSize == INVALID_FILE_SIZE) {
CloseHandle(hFile);
return DetectSystemLanguage();
}
std::vector<char> buffer(fileSize + 1);
DWORD bytesRead;
if (!ReadFile(hFile, buffer.data(), fileSize, &bytesRead, NULL)) {
CloseHandle(hFile);
return DetectSystemLanguage();
}
CloseHandle(hFile);
buffer[fileSize] = '\0';
std::map<std::wstring, std::wstring> settings;
if (LoadLanguageFromJson(buffer.data(), fileSize, settings)) {
auto it = settings.find(L"language");
if (it != settings.end()) {
for (int i = 0; i < g_languageCount; i++) {
if (!wcscmp(it->second.c_str(), g_languages[i].code)) {
return i;
}
}
}
}
return DetectSystemLanguage();
}
static void SaveLanguagePreference() {
wchar_t settingsPath[MAX_PATH];
GetExeDir(settingsPath, MAX_PATH);
wcscat_s(settingsPath, L"\\settings.json");
char utf8[64];
int wideLen = (int)wcslen(g_languages[g_currentLanguage].code);
int utf8Len = WideCharToMultiByte(CP_UTF8, 0, g_languages[g_currentLanguage].code, wideLen, utf8, sizeof(utf8) - 1, NULL, NULL);
if (utf8Len <= 0) return;
utf8[utf8Len] = '\0';
char json[128];
snprintf(json, sizeof(json), "{\n\t\"language\": \"%s\"\n}\n", utf8);
HANDLE hFile = CreateFile(settingsPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return;
DWORD bytesWritten;
WriteFile(hFile, json, (DWORD)strlen(json), &bytesWritten, NULL);
CloseHandle(hFile);
}
static void InitLanguage() {
g_currentLanguage = LoadLanguagePreference();
int loadIdx = g_currentLanguage;
if (loadIdx == 0) {
loadIdx = DetectSystemLanguage();
if (loadIdx < 1 || loadIdx >= g_languageCount) loadIdx = 1;
}
if (!LoadLanguageFile(loadIdx)) {
DEBUG_PRINTF("%s: failed to load language %d, trying English\n", __FUNCTION__, loadIdx);
loadIdx = 1;
LoadLanguageFile(1);
}
}
// -- Existing helpers --------------------------------------------------------
int FindInTray(HWND hwnd) {
for (int i = 0; i < MAXTRAYITEMS; i++) {
if (_hwndItems[i] == hwnd) {
return i;
}
}
return -1;
}
static void PushToStack(HWND hwnd) {
for (int i = 0; i < _stackCount; i++) {
if (_hwndStack[i] == hwnd) {
return;
}
}
if (_stackCount < MAXTRAYITEMS) {
_hwndStack[_stackCount++] = hwnd;
}
}
static void RemoveFromStack(HWND hwnd) {
for (int i = 0; i < _stackCount; i++) {
if (_hwndStack[i] == hwnd) {
for (int j = i; j < _stackCount - 1; j++) {
_hwndStack[j] = _hwndStack[j + 1];
}
_stackCount--;
break;
}
}
}
static bool AddGlobalTrayIcon() {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = GLOBAL_TRAY_ID;
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
nid.uCallbackMessage = WM_TRAYCMD;
nid.uVersion = NOTIFYICON_VERSION;
nid.hIcon = LoadIcon(_hInstance, MAKEINTRESOURCE(IDI_RBTRAY));
wcscpy_s(nid.szTip, GetStr(L"trayNormal"));
if (!Shell_NotifyIcon(NIM_ADD, &nid)) {
DEBUG_PRINTF("%s: NIM_ADD failed for global icon, GetLastError=%lu\n", __FUNCTION__, GetLastError());
return false;
}
DEBUG_PRINTF("%s: NIM_ADD succeeded for global icon\n", __FUNCTION__);
if (!Shell_NotifyIcon(NIM_SETVERSION, &nid)) {
DEBUG_PRINTF("%s: NIM_SETVERSION failed for global icon, GetLastError=%lu\n", __FUNCTION__, GetLastError());
Shell_NotifyIcon(NIM_DELETE, &nid);
return false;
}
DEBUG_PRINTF("%s: NIM_SETVERSION succeeded for global icon\n", __FUNCTION__);
return true;
}
static void UpdateGlobalTrayTip() {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = GLOBAL_TRAY_ID;
nid.uFlags = NIF_TIP;
wcscpy_s(nid.szTip, gPaused ? GetStr(L"trayPaused") : GetStr(L"trayNormal"));
Shell_NotifyIcon(NIM_MODIFY, &nid);
}
static void RemoveGlobalTrayIcon() {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = GLOBAL_TRAY_ID;
Shell_NotifyIcon(NIM_DELETE, &nid);
}
HICON GetWindowIcon(HWND hwnd) {
HICON icon;
if (icon = (HICON)SendMessage(hwnd, WM_GETICON, ICON_SMALL, 0)) {
return icon;
}
if (icon = (HICON)SendMessage(hwnd, WM_GETICON, ICON_BIG, 0)) {
return icon;
}
if (icon = (HICON)GetClassLongPtr(hwnd, GCLP_HICONSM)) {
return icon;
}
if (icon = (HICON)GetClassLongPtr(hwnd, GCLP_HICON)) {
return icon;
}
return LoadIcon(NULL, IDI_WINLOGO);
}
static bool AddToTray(int i) {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = (UINT)i;
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
nid.uCallbackMessage = WM_TRAYCMD;
nid.hIcon = GetWindowIcon(_hwndItems[i]);
GetWindowText(_hwndItems[i], nid.szTip, sizeof(nid.szTip) / sizeof(nid.szTip[0]));
nid.uVersion = NOTIFYICON_VERSION;
if (!Shell_NotifyIcon(NIM_ADD, &nid)) {
DEBUG_PRINTF("%s: NIM_ADD failed for slot %d, GetLastError=%lu\n", __FUNCTION__, i, GetLastError());
return false;
}
DEBUG_PRINTF("%s: NIM_ADD succeeded for slot %d\n", __FUNCTION__, i);
if (!Shell_NotifyIcon(NIM_SETVERSION, &nid)) {
DEBUG_PRINTF("%s: NIM_SETVERSION failed for slot %d, GetLastError=%lu\n", __FUNCTION__, i, GetLastError());
Shell_NotifyIcon(NIM_DELETE, &nid);
return false;
}
DEBUG_PRINTF("%s: NIM_SETVERSION succeeded for slot %d\n", __FUNCTION__, i);
return true;
}
static bool AddWindowToTray(HWND hwnd) {
int i = FindInTray(NULL);
if (i == -1) {
DEBUG_PRINTF("%s: tray full, cannot add hwnd=%p\n", __FUNCTION__, hwnd);
return false;
}
_hwndItems[i] = hwnd;
DEBUG_PRINTF("%s: hwnd=%p at slot %d\n", __FUNCTION__, hwnd, i);
return AddToTray(i);
}
static void MinimizeWindowToTray(HWND hwnd) {
DEBUG_PRINTF("%s: hwnd=%p\n", __FUNCTION__, hwnd);
if (gPaused) {
DEBUG_PRINTF("%s: paused, skipping\n", __FUNCTION__);
return;
}
if ((UINT)GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_MDICHILD) {
DEBUG_PRINTF("%s: skipping MDI child\n", __FUNCTION__);
return;
}
HWND origHwnd = hwnd;
if ((UINT)GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CHILD) {
HWND parent = GetAncestor(hwnd, GA_ROOT);
DEBUG_PRINTF("%s: child window, parent=%p\n", __FUNCTION__, parent);
hwnd = parent;
}
// First minimize to make the application think it was normally minimized
ShowWindow(hwnd, SW_MINIMIZE);
// Wait a brief moment for the minimize to settle
DWORD tick = GetTickCount();
MSG msg;
while (GetTickCount() - tick < 100) {
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Sleep(1);
}
// Now hide the window
ShowWindow(hwnd, SW_HIDE);
BOOL stillVisible = IsWindowVisible(hwnd);
DEBUG_PRINTF("%s: after minimize+hide, stillVisible=%d for hwnd=%p\n",
__FUNCTION__, stillVisible, hwnd);
if (stillVisible) {
// Fallback: direct hide attempts
SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
ShowWindowAsync(hwnd, SW_HIDE);
stillVisible = IsWindowVisible(hwnd);
DEBUG_PRINTF("%s: after fallback hide, stillVisible=%d\n", __FUNCTION__, stillVisible);
}
if (FindInTray(hwnd) == -1) {
if (!AddWindowToTray(hwnd)) {
DEBUG_PRINTF("%s: AddWindowToTray failed for hwnd=%p (orig=%p)\n", __FUNCTION__, hwnd, origHwnd);
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
return;
}
}
PushToStack(hwnd);
}
static bool RemoveFromTray(int i) {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = (UINT)i;
if (!Shell_NotifyIcon(NIM_DELETE, &nid)) {
DEBUG_PRINTF("%s: NIM_DELETE failed, GetLastError=%lu\n", __FUNCTION__, GetLastError());
return false;
}
return true;
}
static bool RemoveWindowFromTray(HWND hwnd) {
int i = FindInTray(hwnd);
if (i == -1) {
DEBUG_PRINTF("%s: hwnd=%p not found in tray\n", __FUNCTION__, hwnd);
return false;
}
DEBUG_PRINTF("%s: removing hwnd=%p from slot %d\n", __FUNCTION__, hwnd, i);
if (!RemoveFromTray(i)) {
return false;
}
_hwndItems[i] = NULL;
RemoveFromStack(hwnd);
return true;
}
static void RestoreWindowFromTray(HWND hwnd) {
DEBUG_PRINTF("%s: restoring hwnd=%p\n", __FUNCTION__, hwnd);
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
RemoveWindowFromTray(hwnd);
}
static void RestoreLastWindowFromTray() {
if (_stackCount == 0) {
DEBUG_PRINTF("%s: no windows in stack\n", __FUNCTION__);
return;
}
HWND hwnd = _hwndStack[_stackCount - 1];
if (IsWindow(hwnd)) {
RestoreWindowFromTray(hwnd);
} else {
RemoveFromStack(hwnd);
}
}
static void RestoreAllWindowsFromTray() {
for (int i = 0; i < MAXTRAYITEMS; i++) {
if (_hwndItems[i]) {
RestoreWindowFromTray(_hwndItems[i]);
}
}
}
static void CloseWindowFromTray(HWND hwnd) {
PostMessage(hwnd, WM_CLOSE, 0, 0);
Sleep(50);
if (IsWindow(hwnd)) {
Sleep(50);
}
if (!IsWindow(hwnd)) {
RemoveWindowFromTray(hwnd);
}
}
void RefreshWindowInTray(HWND hwnd) {
int i = FindInTray(hwnd);
if (i == -1) {
return;
}
if (!IsWindow(hwnd) || IsWindowVisible(hwnd)) {
RemoveWindowFromTray(hwnd);
} else {
NOTIFYICONDATA nid;
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = _hwndHook;
nid.uID = (UINT)i;
nid.uFlags = NIF_TIP;
GetWindowText(hwnd, nid.szTip, sizeof(nid.szTip) / sizeof(nid.szTip[0]));
Shell_NotifyIcon(NIM_MODIFY, &nid);
}
}
static void BuildPopupMenu(HMENU hMenu, bool hasWindow) {
if (hasWindow) {
AppendMenu(hMenu, MF_STRING, IDM_RESTORE, GetStr(L"restoreWindow"));
AppendMenu(hMenu, MF_STRING, IDM_CLOSE, GetStr(L"closeWindow"));
AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
}
AppendMenu(hMenu, MF_STRING, IDM_SETTINGS, GetStr(L"settings"));
AppendMenu(hMenu, MF_STRING, gPaused ? IDM_PAUSE : IDM_PAUSE,
gPaused ? GetStr(L"resume") : GetStr(L"pause"));
AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hMenu, MF_STRING, IDM_ABOUT, GetStr(L"about"));
AppendMenu(hMenu, MF_STRING, IDM_EXIT, GetStr(L"exit"));
}
void ExecuteMenu() {
HMENU hMenu;
POINT point;
hMenu = CreatePopupMenu();
if (!hMenu) {
MessageBox(NULL, GetStr(L"errorCreatingMenu"), GetStr(L"trayNormal"), MB_OK | MB_ICONERROR);
return;
}
BuildPopupMenu(hMenu, _hwndForMenu != NULL);
GetCursorPos(&point);
SetForegroundWindow(_hwndHook);
TrackPopupMenu(hMenu, TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RIGHTALIGN | TPM_BOTTOMALIGN, point.x, point.y, 0, _hwndHook, NULL);
PostMessage(_hwndHook, WM_USER, 0, 0);
DestroyMenu(hMenu);
}
BOOL CALLBACK AboutDlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
switch (Msg) {
case WM_INITDIALOG:
SetWindowText(hWnd, GetStr(L"aboutTitle"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE1, GetStr(L"aboutLine1"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE2, GetStr(L"aboutLine2"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE3, GetStr(L"aboutLine3"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE4, GetStr(L"aboutLine4"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE5, GetStr(L"aboutLine5"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE6, GetStr(L"aboutLine6"));
SetDlgItemText(hWnd, IDC_ABOUT_LINE7, GetStr(L"aboutLine7"));
break;
case WM_CLOSE:
PostMessage(hWnd, WM_COMMAND, IDCANCEL, 0);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
EndDialog(hWnd, TRUE);
break;
case IDCANCEL:
EndDialog(hWnd, FALSE);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
BOOL CALLBACK SettingsDlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
switch (Msg) {
case WM_INITDIALOG:
SetWindowText(hWnd, GetStr(L"settingsTitle"));
SetDlgItemText(hWnd, IDC_STATUS_TEXT, gPaused ? GetStr(L"statusPaused") : GetStr(L"statusRunning"));
SetDlgItemText(hWnd, IDC_PAUSE_CHECK, GetStr(L"pauseMinimize"));
SetDlgItemText(hWnd, IDC_LANGUAGE_STATIC, GetStr(L"language"));
{
HWND hLangCombo = GetDlgItem(hWnd, IDC_LANGUAGE_COMBO);
ComboBox_AddString(hLangCombo, GetStr(L"language_system"));
for (int i = 1; i < g_languageCount; i++) {
ComboBox_AddString(hLangCombo, g_languages[i].nativeName);
}
ComboBox_SetCurSel(hLangCombo, g_currentLanguage);
}
break;
case WM_CLOSE:
PostMessage(hWnd, WM_COMMAND, IDOK, 0);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
{
HWND hLangCombo = GetDlgItem(hWnd, IDC_LANGUAGE_COMBO);
int sel = ComboBox_GetCurSel(hLangCombo);
if (sel != CB_ERR && sel != g_currentLanguage) {
g_currentLanguage = sel;
int loadIdx = g_currentLanguage;
if (loadIdx == 0) {
loadIdx = DetectSystemLanguage();
if (loadIdx < 1 || loadIdx >= g_languageCount) loadIdx = 1;
}
if (LoadLanguageFile(loadIdx)) {
SaveLanguagePreference();
} else {
g_currentLanguage = 0;
LoadLanguageFile(1);
}
UpdateGlobalTrayTip();
}
BOOL pauseChecked = IsDlgButtonChecked(hWnd, IDC_PAUSE_CHECK) == BST_CHECKED;
if (pauseChecked != gPaused) {
gPaused = pauseChecked;
if (_hLib) {
SetPaused(gPaused);
}
UpdateGlobalTrayTip();
DEBUG_PRINTF("%s: pause toggled to %d\n", __FUNCTION__, gPaused);
}
EndDialog(hWnd, TRUE);
break;
}
case IDCANCEL:
EndDialog(hWnd, FALSE);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
LRESULT CALLBACK HookWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_COMMAND:
DEBUG_PRINTF("%s: WM_COMMAND wParam=%llx\n", __FUNCTION__, (long long int)wParam);
switch (LOWORD(wParam)) {
case IDM_RESTORE:
if (_hwndForMenu) {
RestoreWindowFromTray(_hwndForMenu);
}
break;
case IDM_CLOSE:
if (_hwndForMenu) {
CloseWindowFromTray(_hwndForMenu);
}
break;
case IDM_ABOUT:
DialogBox(_hInstance, MAKEINTRESOURCE(IDD_ABOUT), hwnd, (DLGPROC)AboutDlgProc);
break;
case IDM_SETTINGS:
DialogBox(_hInstance, MAKEINTRESOURCE(IDD_SETTINGS), hwnd, (DLGPROC)SettingsDlgProc);
break;
case IDM_PAUSE:
gPaused = !gPaused;
if (_hLib) {
SetPaused(gPaused);
}
UpdateGlobalTrayTip();
DEBUG_PRINTF("%s: pause toggled to %d\n", __FUNCTION__, gPaused);
break;
case IDM_EXIT:
PostMessage(hwnd, WM_CLOSE, 0, 0);
break;
}
break;
case WM_ADDTRAY:
DEBUG_PRINTF("%s: WM_ADDTRAY hwnd=%p\n", __FUNCTION__, (HWND)lParam);
MinimizeWindowToTray((HWND)lParam);
break;
case WM_REMTRAY:
DEBUG_PRINTF("%s: WM_REMTRAY hwnd=%p\n", __FUNCTION__, (HWND)lParam);
RestoreWindowFromTray((HWND)lParam);
break;
case WM_REFRTRAY:
DEBUG_PRINTF("%s: WM_REFRTRAY hwnd=%p\n", __FUNCTION__, (HWND)lParam);
RefreshWindowInTray((HWND)lParam);
break;
case WM_TRAYCMD:
DEBUG_PRINTF("%s: WM_TRAYCMD wParam=%llx, lParam=%llx\n", __FUNCTION__, (long long int)wParam, (long long int)lParam);
if (wParam == GLOBAL_TRAY_ID) {
switch ((UINT)lParam) {
case NIN_SELECT:
if (_stackCount > 0) {
RestoreLastWindowFromTray();
}
break;
case WM_CONTEXTMENU:
_hwndForMenu = NULL;
ExecuteMenu();
break;
case WM_MOUSEMOVE:
break;
}
} else {
switch ((UINT)lParam) {
case NIN_SELECT:
RestoreWindowFromTray(_hwndItems[wParam]);
break;
case WM_CONTEXTMENU:
_hwndForMenu = _hwndItems[wParam];
ExecuteMenu();
break;
case WM_MOUSEMOVE:
RefreshWindowInTray(_hwndItems[wParam]);
break;
}
}
break;
case WM_HOTKEY:
{
if (wParam == 1) {
DEBUG_PRINTF("%s: WM_HOTKEY restore last\n", __FUNCTION__);
RestoreLastWindowFromTray();
break;
}
HWND fgWnd = GetForegroundWindow();
if (!fgWnd)
break;
DEBUG_PRINTF("%s: WM_HOTKEY minimize, fgWnd=%p, visible=%d\n",
__FUNCTION__, fgWnd, IsWindowVisible(fgWnd));
// If window is already hidden (but somehow not in tray), skip
if (!IsWindowVisible(fgWnd)) {
DEBUG_PRINTF("%s: fgWnd already hidden\n", __FUNCTION__);
break;
}
// If already in tray but visible again, re-hide via MinimizeWindowToTray
if (FindInTray(fgWnd) != -1) {
DEBUG_PRINTF("%s: fgWnd in tray but visible, re-hiding\n", __FUNCTION__);
MinimizeWindowToTray(fgWnd);
break;
}
LONG style = GetWindowLong(fgWnd, GWL_STYLE);
if (!(style & WS_MINIMIZEBOX)) {
DEBUG_PRINTF("%s: fgWnd has no WS_MINIMIZEBOX, skipping\n", __FUNCTION__);
break;
}
MinimizeWindowToTray(fgWnd);
break;
}
case WM_CLOSE:
RestoreAllWindowsFromTray();
RemoveGlobalTrayIcon();
DestroyWindow(hwnd);
break;
case WM_DESTROY:
if (_hLib) {
UnRegisterHook();
FreeLibrary(_hLib);
_hLib = NULL;
}
PostQuitMessage(0);
break;
default:
if (msg == WM_TASKBAR_CREATED) {
AddGlobalTrayIcon();
for (int i = 0; i < MAXTRAYITEMS; i++) {
if (_hwndItems[i]) {
AddToTray(i);
}
}
}
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE /*hPrevInstance*/, _In_ LPSTR /*szCmdLine*/, _In_ int /*iCmdShow*/) {
_hInstance = hInstance;
int argc;
LPWSTR * argv = CommandLineToArgvW(GetCommandLineW(), &argc);
bool shouldExit = false;
bool useHook = true;
for (int a = 0; a < argc; ++a) {
if (!wcscmp(argv[a], L"--exit")) {
shouldExit = true;
}
if (!wcscmp(argv[a], L"--no-hook")) {
useHook = false;
}
if (!wcscmp(argv[a], L"--debug")) {
gDebug = TRUE;
}
}
_hwndHook = FindWindow(NAME, NAME);
if (_hwndHook) {
if (shouldExit) {
PostMessage(_hwndHook, WM_CLOSE, 0, 0);
} else {
MessageBox(NULL, GetStr(L"alreadyRunning"), GetStr(L"trayNormal"), MB_OK | MB_ICONINFORMATION);
}
return 0;
}
InitLanguage();
DEBUG_PRINTF("%s: starting, useHook=%d, debug=%d\n", __FUNCTION__, useHook, gDebug);
if (useHook) {
if (!(_hLib = LoadLibrary(L"RBHook.dll"))) {
DEBUG_PRINTF("%s: failed to load RBHook.dll\n", __FUNCTION__);
MessageBox(NULL, GetStr(L"errorLoadingDll"), GetStr(L"trayNormal"), MB_OK | MB_ICONERROR);
return 0;
}
if (!RegisterHook(_hLib)) {
DEBUG_PRINTF("%s: failed to register hooks\n", __FUNCTION__);
MessageBox(NULL, GetStr(L"errorSettingHook"), GetStr(L"trayNormal"), MB_OK | MB_ICONERROR);
return 0;
}
if (gDebug) {
SetDebugMode(TRUE);
}
}
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = HookWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = NAME;
if (!RegisterClass(&wc)) {
MessageBox(NULL, GetStr(L"errorCreatingWindow"), GetStr(L"trayNormal"), MB_OK | MB_ICONERROR);
return 0;
}
if (!(_hwndHook = CreateWindow(NAME, NAME, WS_OVERLAPPED, 0, 0, 0, 0, (HWND)NULL, (HMENU)NULL, (HINSTANCE)hInstance, (LPVOID)NULL))) {
MessageBox(NULL, GetStr(L"errorCreatingWindow"), GetStr(L"trayNormal"), MB_OK | MB_ICONERROR);
return 0;
}
for (int i = 0; i < MAXTRAYITEMS; i++) {
_hwndItems[i] = NULL;
}
WM_TASKBAR_CREATED = RegisterWindowMessage(L"TaskbarCreated");
AddGlobalTrayIcon();
BOOL registeredHotKey0 = RegisterHotKey(_hwndHook, 0, MOD_ALT | MOD_CONTROL, VK_DOWN);
if (!registeredHotKey0) {
DEBUG_PRINTF("%s: RegisterHotKey Ctrl+Alt+Down failed, err=%lu\n", __FUNCTION__, GetLastError());
} else {
DEBUG_PRINTF("%s: hotkey Ctrl+Alt+Down registered\n", __FUNCTION__);
}
BOOL registeredHotKey1 = RegisterHotKey(_hwndHook, 1, MOD_ALT | MOD_CONTROL, VK_UP);
if (!registeredHotKey1) {
DEBUG_PRINTF("%s: RegisterHotKey Ctrl+Alt+Up failed, err=%lu\n", __FUNCTION__, GetLastError());
} else {
DEBUG_PRINTF("%s: hotkey Ctrl+Alt+Up registered\n", __FUNCTION__);
}
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (registeredHotKey0) {
UnregisterHotKey(_hwndHook, 0);
}
if (registeredHotKey1) {
UnregisterHotKey(_hwndHook, 1);
}
return (int)msg.wParam;
}