This repository was archived by the owner on Jan 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathctSpaces.cpp
More file actions
1670 lines (1597 loc) · 63.2 KB
/
ctSpaces.cpp
File metadata and controls
1670 lines (1597 loc) · 63.2 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
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
// ctSpaces.cpp
// Because I didn't have the paitence to port this from the ground up, I used Gemini 2.5 Pro for heavylifting and filled in the gaps.
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "dwmapi.lib")
#pragma comment(lib, "uxtheme.lib")
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "Propsys.lib")
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "Version.lib")
#include <windows.h>
#include <commctrl.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <dwmapi.h>
#include <uxtheme.h>
#include <propkey.h>
#include <propvarutil.h>
#include <gdiplus.h>
#include <shobjidl.h>
#include <memory>
#include <string>
#include <vector>
#include <filesystem>
#include <format>
#include <ranges>
#include <functional>
#include <regex>
#include <thread>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip> // FIX: Added for std::put_time
#include <mutex>
#include <map>
#include "resource.h" // For IDR_7ZA and IDR_DEFAULT_7Z
namespace fs=std::filesystem;
struct IconButtonInfo{
int id;
HWND hWnd;
std::wstring symbol;
std::wstring tooltip;
std::function<void()> handler;
};
#pragma pack(push, 1)
typedef struct{
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
DWORD dwImageOffset;
} ICONDIRENTRY;
typedef struct{
WORD idReserved;
WORD idType;
WORD idCount;
ICONDIRENTRY idEntries[1];
} ICONDIR;
#pragma pack(pop)
enum class ProfileType{
Standard,
Default,
Temporary
};
const std::wstring APP_ALIAS=L"ctSpaces";
const std::wstring APP_VERSION=L"2.2";
const std::wstring APP_TITLE=std::format(L"{} v{}b",APP_ALIAS,APP_VERSION);
const std::wstring GUI_CLASS_NAME=L"ctSpacesLauncherClass";
ULONG_PTR g_gdiplusToken;
HINSTANCE g_hInst;
HWND g_hGui=NULL;
HWND g_hComboClient=NULL;
HWND g_hValidationTooltip=NULL;
HWND g_hBtnGo=NULL;
HFONT g_hFont=NULL;
fs::path g_sDataDir;
fs::path g_sEdgePath;
std::wstring g_sLastValidComboText=L"";
std::wstring g_sClientSel=L"";
std::jthread g_watcherThread;
std::mutex g_activeProfilesMutex;
std::atomic<bool> g_isWatcherRunning=false;
std::map<std::wstring,HICON> g_iconCache;
std::mutex g_iconCacheMutex;
IShellLink* shellLink=NULL;
#define WM_APP_TASK_COMPLETE (WM_APP + 1)
const std::vector<std::wstring> aKeepDefault={
L"Local State",
L"Last Version",
L"Last Browser",
L"FirstLaunchAfterInstallation",
L"First Run",
L"ctSpaces",
L"DevToolsActivePort",
L"Default\\Shortcuts",
L"Default\\Shortcuts-journal", L"Default\\Secure Preferences",
L"Default\\Preferences",
L"Default\\Favicons-journal",
L"Default\\Favicons",
L"Default\\Bookmarks",
L"Default\\Extension State",
L"Default\\Extensions",
L"Default\\Local Extension Settings",
L"Default\\Asset Store",
L"Default\\Extension Rules",
L"Default\\Extension Scripts"
};
const std::vector<std::wstring> aKeepActive={
L"client.ico",
L"client.png",
L"ctSpaces",
L"Local State",
L"Last Version",
L"Last Browser",
L"FirstLaunchAfterInstallation",
L"First Run",
L"DevToolsActivePort",
L"Default\\History",
L"Default\\Shortcuts",
L"Default\\Shortcuts-journal",
L"Default\\Secure Preferences",
L"Default\\Preferences",
L"Default\\Favicons-journal",
L"Default\\Favicons",
L"Default\\Bookmarks",
L"Default\\Extension State",
L"Default\\Extension Rules",
L"Default\\Extension Scripts",
L"Default\\Extensions",
L"Default\\Asset Store",
L"Default\\Local Extension Settings",
L"CertificateRevocation",
L"AutoLaunchProtocolsComponent",
L"Default\\History",
L"Default\\Web Data",
L"Default\\Web Data-journal",
L"Default\\Login Data",
L"Default\\Login Data-journal",
L"Default\\Favicons",
L"Default\\Favicons-journal",
L"Default\\MediaDeviceSalts",
L"Default\\MediaDeviceSalts-journal",
L"Default\\CdmStorage.db",
L"Default\\CdmStorage.db-journal",
L"Default\\DIPS",
L"Default\\DIPS-journal",
L"Default\\Local Storage",
L"Default\\WebStorage",
//L"Default\\Service Worker\\Database",
L"Default\\ClientCertificates",
L"Default\\blob_storage",
L"Default\\Session Storage",
L"Default\\IndexedDB",
L"Default\\Network",
L"Default\\Sessions"
};
/*
PKIMetadata\
WebAssistDataBase
Web Data
Web Data-journal
Prefrences
Login Data
Login Data-journal
History
History-journal
Sessions\
Network\
Asset Store\
*/
std::map<std::wstring,DWORD> g_activeProfiles;
std::vector<IconButtonInfo> g_iconButtons;
std::vector<std::jthread> g_reaperThreads;
void GuiProfOpen();
void GuiSetIcon();
void GuiProfReset();
void GuiProfUpd();
void GuiOpenDef();
void GuiOpenTmp();
bool IsValidFilenameChar(wchar_t c);
std::wstring SanitizeName(const std::wstring& name);
void UpdateClientsComboBox();
void SetUiState(bool enabled);
void LaunchAndManageProfile(const std::wstring& clientName,bool isTemp,bool isDefault);
bool ExtractResourceToFile(UINT resourceID,const fs::path& destPath);
bool RunCommand(const std::wstring& command,const fs::path& workingDir);
bool extDef(const fs::path& profileDataPath);
void CleanupProfile(const fs::path& profilePath,const std::vector<std::wstring>& keepList);
void SetWindowAppId(HWND hWnd,const std::wstring& appId);
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE,int);
std::wstring AnsiToWide(const std::string& str);
std::vector<std::wstring> GetSupportedImageTypes();
bool ConvertImageToIcon(const fs::path& sourceImagePath,const fs::path& destIconPath);
bool SaveIconsToFile(const fs::path& filePath,std::vector<HICON>& icons,bool compressLargeImages=true);
std::vector<BYTE> CompressBitmapToPng(HBITMAP hBitmap);
CLSID GetEncoderClsid(const WCHAR* format);
HICON Create32BitHICON(HICON hIcon);
bool IsAlphaBitmap(HBITMAP hBitmap);
void EnsureWatcherIsRunning();
void WatcherThread();
void ReaperThread(DWORD pid,std::wstring clientName,ProfileType type);
DWORD LaunchProfile(const std::wstring& clientName,bool isTemp,bool isDefault);
bool FindEdgePath();
void TerminateAllProfiles();
std::wstring GetExeVersion(const fs::path& filePath);
bool chkUpdate();
bool doInstall();
HWND CreateToolTip(HWND toolHWND, HWND hDlg, PTSTR pszText);
static void PostTaskComplete(const std::wstring& name);
static void LaunchProfileAsync(const std::wstring& name, bool isTemp, bool isDefault);
void GuiProfDel();
inline void EnsureMouseVisible();
inline void FocusClientEdit();
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,_In_opt_ HINSTANCE,_In_ LPWSTR lpCmdLine,_In_ int nCmdShow){
CoInitializeEx(NULL,COINIT_APARTMENTTHREADED|COINIT_DISABLE_OLE1DDE);
PWSTR path=NULL;
if(SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData,0,NULL,&path))){
g_sDataDir=fs::path(path)/"InfinitySys"/"ctSpaces";
CoTaskMemFree(path);
}
std::filesystem::create_directories(g_sDataDir);
wchar_t currentExePathStr[MAX_PATH];
GetModuleFileNameW(NULL,currentExePathStr,MAX_PATH);
fs::path currentExePath(currentExePathStr);
const wchar_t* mutexName=L"Global\\{E19C159D-62C3-4412-A0A3-1A55A67C8C56}";
HANDLE hMutex=CreateMutexW(NULL,TRUE,mutexName);
if(hMutex!=NULL&&GetLastError()==ERROR_ALREADY_EXISTS){
HWND hExistingWnd=FindWindowW(GUI_CLASS_NAME.c_str(),NULL);
if(hExistingWnd){
DWORD existingProcId;
GetWindowThreadProcessId(hExistingWnd,&existingProcId);
HANDLE hExistingProcess=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,existingProcId);
if(hExistingProcess){
wchar_t existingExePathStr[MAX_PATH]={0};
DWORD pathSize=MAX_PATH;
QueryFullProcessImageNameW(hExistingProcess,0,existingExePathStr,&pathSize);
CloseHandle(hExistingProcess);
if(!fs::equivalent(currentExePath,existingExePathStr)){
MessageBoxW(
NULL,
L"A different version of ctSpaces is already running.\n\nPlease close the other instance before installing or running this version.",
L"Update Conflict",
MB_OK|MB_ICONWARNING
);
ReleaseMutex(hMutex);
CloseHandle(hMutex);
CoUninitialize();
return 0;
}
}
ShowWindow(hExistingWnd,SW_RESTORE);
SetForegroundWindow(hExistingWnd);
}
ReleaseMutex(hMutex);
CloseHandle(hMutex);
CoUninitialize();
return 0;
}
bool shouldRun=false;
fs::path installedExePath=g_sDataDir/L"ctSpaces.exe";
if(fs::exists(installedExePath)){
shouldRun=chkUpdate();
} else{
shouldRun=doInstall();
}
if(!shouldRun){
CoUninitialize();
return 0;
}
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
if(!FindEdgePath()){
MessageBox(NULL,L"Microsoft Edge could not be found in standard installation locations. Please ensure it is installed.",L"Application Error",MB_OK|MB_ICONERROR);
CoUninitialize();
return 1;
}
Gdiplus::GdiplusStartup(&g_gdiplusToken,&gdiplusStartupInput,NULL);
ExtractResourceToFile(IDR_7ZAX64,g_sDataDir/"7za.exe");
ExtractResourceToFile(IDR_DEFPROF,g_sDataDir/"Default.7z");
INITCOMMONCONTROLSEX icex={sizeof(INITCOMMONCONTROLSEX), ICC_WIN95_CLASSES};
InitCommonControlsEx(&icex);
bool useTrdLayout=(wcsstr(lpCmdLine,L"~!Trd:P")!=nullptr);
g_iconButtons={
{ 200, NULL, L"Ico", L"Set Profile Icon", GuiSetIcon },
{ 201, NULL, L"Rst", L"Reset Selected Profile to Default", GuiProfReset },
{ 202, NULL, L"Upd", L"Update Selected Profile with Default (Overwrites Profile /w Default)", GuiProfUpd },
{ 203, NULL, L"Def", L"Modify Default Profile", GuiOpenDef },
{ 204, NULL, L"Tmp", L"Launch temporary profile", GuiOpenTmp },
{ 205, NULL, L"Del", L"Delete Profile", GuiProfDel },
};
if(useTrdLayout){
std::vector<IconButtonInfo> trdLayoutButtons={
g_iconButtons[0],
g_iconButtons[4],
g_iconButtons[2],
g_iconButtons[1],
g_iconButtons[3],
g_iconButtons[5]
};
g_iconButtons.swap(trdLayoutButtons);
}
MyRegisterClass(hInstance);
if(!InitInstance(hInstance,nCmdShow)){
return FALSE;
}
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
// intercept Enter when focus is in the combo or its edit
if (msg.message == WM_KEYDOWN && msg.wParam == VK_RETURN) {
HWND hFocus = GetFocus();
if (hFocus == g_hComboClient ||
(hFocus && GetParent(hFocus) == g_hComboClient)) {
// pretend the Go button was pressed
SendMessage(g_hGui,
WM_COMMAND,
MAKELONG(IDOK, BN_CLICKED),
(LPARAM)g_hBtnGo);
// don't let the dialog logic eat this
continue;
}
}
if (!IsDialogMessage(g_hGui, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//while(GetMessage(&msg,nullptr,0,0)){
// if(!IsDialogMessage(g_hGui,&msg)){
// TranslateMessage(&msg);
// DispatchMessage(&msg);
// }
//}
Gdiplus::GdiplusShutdown(g_gdiplusToken);
CoUninitialize();
return (int)msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance){
WNDCLASSEXW wcex={};
wcex.cbSize=sizeof(WNDCLASSEXW);
wcex.style=CS_HREDRAW|CS_VREDRAW;
wcex.lpfnWndProc=WndProc;
wcex.hInstance=hInstance;
wcex.hCursor=LoadCursor(nullptr,IDC_ARROW);
wcex.hbrBackground=(HBRUSH)(COLOR_BTNFACE+1);
wcex.lpszClassName=GUI_CLASS_NAME.c_str();
wcex.lpszMenuName=NULL;
return RegisterClassExW(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance,int nCmdShow){
g_hInst=hInstance;
const int iGuiW=256+64+16+8;
const int iGuiH=128+4;
const int iGuiM=4;
const int iGuiCtrlW=(iGuiW-iGuiM*2);
g_hFont=CreateFontW(15,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH|FF_MODERN,L"Consolas");
g_hGui=CreateWindowW(GUI_CLASS_NAME.c_str(),APP_TITLE.c_str(),WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX,CW_USEDEFAULT,0,iGuiW,iGuiH,nullptr,nullptr,hInstance,nullptr);
if(!g_hGui) return FALSE;
HICON hAppIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_CTSPACES));
if(hAppIcon){
SendMessage(g_hGui,WM_SETICON,ICON_BIG,(LPARAM)hAppIcon);
SendMessage(g_hGui,WM_SETICON,ICON_SMALL,(LPARAM)hAppIcon);
}
BOOL isDarkMode=TRUE;
DwmSetWindowAttribute(g_hGui,DWMWA_USE_IMMERSIVE_DARK_MODE,&isDarkMode,sizeof(isDarkMode));
CreateWindowW(L"STATIC",L"Select or type the client name:",WS_CHILD|WS_VISIBLE,iGuiM,iGuiM,iGuiCtrlW,17,g_hGui,(HMENU)101,hInstance,nullptr);
g_hValidationTooltip=CreateWindowEx(WS_EX_TOPMOST,TOOLTIPS_CLASS,NULL,TTS_BALLOON|TTS_NOPREFIX|TTS_ALWAYSTIP,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,g_hGui,NULL,g_hInst,NULL);
SendMessage(g_hValidationTooltip,TTM_SETMAXTIPWIDTH,0,400);
g_hComboClient=CreateWindowW(L"COMBOBOX",L"",WS_CHILD|WS_VISIBLE|CBS_DROPDOWN|CBS_AUTOHSCROLL|WS_VSCROLL,iGuiM,17+iGuiM*2,iGuiCtrlW-iGuiM*4,150,g_hGui,(HMENU)102,hInstance,nullptr);
TOOLINFOW tic={sizeof(TOOLINFOW)};
tic.uFlags=TTF_SUBCLASS|TTF_TRANSPARENT|TTF_TRACK;
tic.hwnd=g_hGui;
tic.hinst=g_hInst;
tic.uId=(UINT_PTR)g_hComboClient;
tic.lpszText=LPSTR_TEXTCALLBACK;
SendMessage(g_hValidationTooltip,TTM_ADDTOOL,0,(LPARAM)&tic);
g_hBtnGo=CreateWindowW(L"BUTTON",L"Go",WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON,(iGuiCtrlW/2)-32-4,(25*2)+iGuiM,64,33,g_hGui,(HMENU)IDOK,hInstance,nullptr);
//HWND hToolTip=CreateWindowEx(0,TOOLTIPS_CLASS,NULL,TTS_ALWAYSTIP|TTS_NOPREFIX,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,g_hGui,NULL,g_hInst,NULL);
const int iBtnS=20,iBtnM=2;
int iBtnL=iGuiCtrlW-iGuiM*2-((iBtnS+iBtnM)*(static_cast<int>(g_iconButtons.size())+1))-8;
for (size_t ix=0; ix<g_iconButtons.size(); ++ix) {
int iBtnT=iGuiH-((iBtnS+iBtnM)*(2-((ix/4)%((g_iconButtons.size()/4)*4))))-32-6;
int xPos=iBtnL+((iBtnS+iBtnM+10)*(static_cast<int>(ix%4)+1));
g_iconButtons[ix].hWnd=CreateWindowW(L"BUTTON",g_iconButtons[ix].symbol.c_str(),WS_CHILD|WS_VISIBLE,xPos,iBtnT,iBtnS+10,iBtnS,g_hGui,(HMENU)(INT_PTR)g_iconButtons[ix].id,g_hInst,nullptr);
CreateToolTip(g_iconButtons[ix].hWnd,g_hGui,(LPWSTR)g_iconButtons[ix].tooltip.c_str());
}
EnumChildWindows(g_hGui,[](HWND hwnd,LPARAM lParam)->BOOL{SendMessage(hwnd,WM_SETFONT,(WPARAM)lParam,TRUE);return TRUE;},(LPARAM)g_hFont);
UpdateClientsComboBox();
SetFocus(g_hComboClient);
ShowWindow(g_hGui,nCmdShow);
UpdateWindow(g_hGui);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam){
switch(message){
case WM_COMMAND:{
int wmId=LOWORD(wParam);
int wmEvent=HIWORD(wParam);
if(wmId==102){
if(wmEvent==CBN_EDITCHANGE){
wchar_t buffer[256];
GetWindowText(g_hComboClient,buffer,256);
std::wstring currentText=buffer;
std::wstring sanitizedText;
bool hasInvalidChar=false;
for(wchar_t c:currentText){
if(IsValidFilenameChar(c)){
sanitizedText+=c;
} else{
hasInvalidChar=true;
}
}
if(GetAsyncKeyState(VK_BACK)&0x8000||GetAsyncKeyState(VK_DELETE)&0x8000){
if(!hasInvalidChar){
g_sLastValidComboText=currentText;
TOOLINFOW ti={sizeof(TOOLINFOW)};
ti.hwnd=g_hGui;
ti.uId=(UINT_PTR)g_hComboClient;
SendMessage(g_hValidationTooltip,TTM_TRACKACTIVATE,FALSE,(LPARAM)&ti);
}
return 0;
}
if(hasInvalidChar){
SetWindowText(g_hComboClient,g_sLastValidComboText.c_str());
SendMessage(g_hComboClient,CB_SETEDITSEL,0,MAKELPARAM(g_sLastValidComboText.length(),g_sLastValidComboText.length()));
TOOLINFOW ti={sizeof(TOOLINFOW)};
ti.hwnd=g_hGui;
ti.uFlags=TTF_ABSOLUTE;
ti.uId=(UINT_PTR)g_hComboClient;
ti.lpszText=(LPWSTR)L"A client name can't contain any of the following characters:\n \\ / : * ? \" < > |";
SendMessage(g_hValidationTooltip,TTM_UPDATETIPTEXT,0,(LPARAM)&ti);
RECT rect;
GetWindowRect(g_hComboClient,&rect);
SendMessage(g_hValidationTooltip,TTM_TRACKPOSITION,0,MAKELPARAM(rect.left+4,rect.bottom-4));
SendMessage(g_hValidationTooltip,TTM_TRACKACTIVATE,TRUE,(LPARAM)&ti);
SendMessage(g_hComboClient,CB_SHOWDROPDOWN,FALSE,0);
} else{
g_sLastValidComboText=currentText;
TOOLINFOW ti={sizeof(TOOLINFOW)};
ti.hwnd=g_hGui;
ti.uId=(UINT_PTR)g_hComboClient;
SendMessage(g_hValidationTooltip,TTM_TRACKACTIVATE,FALSE,(LPARAM)&ti);
if(currentText.length()>0){
int ciMatchIdx = -1;
int csMatchIdx = -1;
wchar_t buf[256];
for(int i=0;i<(int)SendMessage(g_hComboClient,CB_GETCOUNT,0,0);++i){
SendMessage(g_hComboClient,CB_GETLBTEXT,i,(LPARAM)buf);
std::wstring listItem=buf;
if (csMatchIdx==-1&&listItem.size()>=currentText.size()&&listItem.compare(0,currentText.size(),currentText)==0){
csMatchIdx=i;
break;
}
if (ciMatchIdx==-1&&listItem.size()>=currentText.size()&&_wcsnicmp(listItem.c_str(),currentText.c_str(),currentText.size())==0){
ciMatchIdx=i;
}
}
if (csMatchIdx!=-1) {
SendMessage(g_hComboClient, CB_GETLBTEXT, csMatchIdx, (LPARAM)buf);
SendMessage(g_hComboClient, CB_SETCURSEL, csMatchIdx, 0);
SendMessage(g_hComboClient, CB_SHOWDROPDOWN, TRUE, 0);
EnsureMouseVisible();
SetWindowText(g_hComboClient, buf);
}else if (ciMatchIdx!=-1) {
SendMessage(g_hComboClient, CB_SETCURSEL, ciMatchIdx, 0);
SendMessage(g_hComboClient, CB_SHOWDROPDOWN, TRUE, 0);
EnsureMouseVisible();
SetWindowText(g_hComboClient, currentText.c_str());
}else{
SendMessage(g_hComboClient,CB_SHOWDROPDOWN,FALSE,0);
SetWindowText(g_hComboClient, currentText.c_str());
}
SendMessage(g_hComboClient, CB_SETEDITSEL, 0, MAKELPARAM((DWORD)currentText.length(), (DWORD)-1));
}else{
SendMessage(g_hComboClient, CB_SHOWDROPDOWN, FALSE, 0);
}
}
}
} else if(wmId==IDOK){
GuiProfOpen();
} else{
auto it=std::find_if(g_iconButtons.begin(),g_iconButtons.end(),[wmId](const auto& btn){
return btn.id==wmId;
});
if(it!=g_iconButtons.end()&&it->handler){
it->handler();
}
}
return 0;
}
case WM_CTLCOLORBTN:
case WM_CTLCOLORSTATIC: {
HDC hdcControl=(HDC)wParam;
SetTextColor(hdcControl,GetThemeSysColor(NULL,COLOR_BTNTEXT));
SetBkColor(hdcControl,GetThemeSysColor(NULL,COLOR_BTNFACE));
return (INT_PTR)GetThemeSysColorBrush(NULL,COLOR_BTNFACE);
}
case WM_APP_TASK_COMPLETE: {
std::wstring clientName;
if (lParam) {
std::wstring* pName = reinterpret_cast<std::wstring*>(lParam);
clientName = *pName;
delete pName;
}
else {
wchar_t clientNameBuffer[256];
GetWindowText(g_hComboClient, clientNameBuffer, 256);
clientName = SanitizeName(clientNameBuffer);
}
SetUiState(true);
if (!clientName.empty()&&clientName!=L"Temp"&&clientName!=L"Default"){
g_sClientSel=clientName;
UpdateClientsComboBox();
LRESULT idx=SendMessage(g_hComboClient,CB_FINDSTRINGEXACT,(WPARAM)-1,(LPARAM)clientName.c_str());
if (idx!=CB_ERR){
SendMessage(g_hComboClient,CB_SETCURSEL,(WPARAM)idx,0);
}else{
SetWindowText(g_hComboClient,clientName.c_str());
}
}
FocusClientEdit();
return 0;
}
case WM_CLOSE: {
bool hasActiveProfiles=false;
{
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if(!g_activeProfiles.empty()){
hasActiveProfiles=true;
}
}
if(hasActiveProfiles){
int result=MessageBox(
hWnd,
L"There are active profiles running. Would you like to exit and close all open profiles?",
L"Confirm Exit",
MB_OKCANCEL|MB_ICONWARNING
);
if(result==IDOK){
TerminateAllProfiles();
DestroyWindow(hWnd);
}
} else{
DestroyWindow(hWnd);
}
return 0;
}
case WM_DESTROY: {
if(g_hFont) DeleteObject(g_hFont);
PostQuitMessage(0);
break;
}
case WM_ACTIVATE: {
if (LOWORD(wParam) != WA_INACTIVE) {
FocusClientEdit();
}
return 0;
}
case WM_SETFOCUS: {
FocusClientEdit();
return 0;
}
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
void GuiProfOpen() {
SetUiState(false);
wchar_t clientNameBuffer[256];
GetWindowText(g_hComboClient, clientNameBuffer, 256);
std::wstring clientName = SanitizeName(clientNameBuffer);
if (clientName.empty()) {
MessageBox(g_hGui, L"Please select or enter a valid client name.", L"Input Error", MB_OK | MB_ICONWARNING);
SetUiState(true);
return;
}
{
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if (g_activeProfiles.count(clientName)) {
MessageBox(g_hGui, L"This profile is already open.", L"Already Running", MB_OK | MB_ICONINFORMATION);
SetUiState(true);
return;
}
}
LaunchProfileAsync(clientName,false,false);
}
void GuiSetIcon(){
SetUiState(false);
wchar_t clientNameBuffer[256];
GetWindowText(g_hComboClient,clientNameBuffer,256);
std::wstring clientName=SanitizeName(clientNameBuffer);
if(clientName.empty()){
MessageBox(g_hGui,L"Please select a client first.",L"Warning",MB_OK|MB_ICONWARNING);
SetUiState(true);
return;
}
std::wstring filter;
std::wstring allSupportedExtensions=L"*.ico";
std::vector<std::wstring> types=GetSupportedImageTypes();
for(const auto& type:types){
allSupportedExtensions+=L";*."+type;
}
filter+=L"Supported Image Files ("+allSupportedExtensions+L")";
filter+=L'\0';
filter+=allSupportedExtensions;
filter+=L'\0';
filter+=L"Icon Files (*.ico)";
filter+=L'\0';
filter+=L"*.ico";
filter+=L'\0';
filter+=L"All Files (*.*)";
filter+=L'\0';
filter+=L"*.*";
filter+=L'\0';
filter+=L'\0';
wchar_t szFile[MAX_PATH]={0};
OPENFILENAMEW ofn={0};
ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=g_hGui;
ofn.lpstrFile=szFile;
ofn.nMaxFile=sizeof(szFile)/sizeof(wchar_t);
ofn.lpstrFilter=filter.c_str();
ofn.nFilterIndex=1;
ofn.Flags=OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
if(GetOpenFileNameW(&ofn)){
fs::path sourcePath(ofn.lpstrFile);
fs::path destIconPath=g_sDataDir/"Sites"/clientName/"client.ico";
fs::create_directories(destIconPath.parent_path());
bool success=false;
std::wstring errorDetails;
try{
if(_wcsicmp(sourcePath.extension().c_str(),L".ico")==0){
fs::copy_file(sourcePath,destIconPath,fs::copy_options::overwrite_existing);
success=true;
} else{
success=ConvertImageToIcon(sourcePath,destIconPath);
if(!success){
errorDetails=L"Could not convert image to icon format.";
}
}
} catch(const fs::filesystem_error& e){
success=false;
errorDetails=AnsiToWide(e.what());
}
if(success){
MessageBox(g_hGui,L"Icon has been configured.",L"Success",MB_OK|MB_ICONINFORMATION);
std::lock_guard<std::mutex> cacheLock(g_iconCacheMutex);
if(g_iconCache.count(clientName)){
if(g_iconCache[clientName]){
DestroyIcon(g_iconCache[clientName]);
}
HICON hNewIcon=(HICON)LoadImageW(NULL,destIconPath.c_str(),IMAGE_ICON,0,0,LR_LOADFROMFILE|LR_DEFAULTSIZE|LR_SHARED);
g_iconCache[clientName]=hNewIcon;
}
} else{
std::wstring errorMsg=L"Failed to set icon.";
if(!errorDetails.empty()){
errorMsg+=L"\n\nDetails: "+errorDetails;
}
MessageBox(g_hGui,errorMsg.c_str(),L"Error",MB_OK|MB_ICONERROR);
}
}
SetUiState(true);
}
void GuiProfReset(){
SetUiState(false);
wchar_t clientNameBuffer[256];
GetWindowText(g_hComboClient,clientNameBuffer,256);
std::wstring clientName=SanitizeName(clientNameBuffer);
if(clientName.empty()){
MessageBox(g_hGui,L"Please select a client first.",L"Warning",MB_OK|MB_ICONWARNING);
SetUiState(true);
return;
}
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if(g_activeProfiles.count(clientName)){
MessageBox(g_hGui,L"Cannot reset a profile that is currently active.",L"Action Denied",MB_OK|MB_ICONWARNING);
SetUiState(true);
return;
}
if(MessageBox(g_hGui,L"This will completely delete and reset the profile. Are you sure?",L"Confirm Reset",MB_YESNO|MB_ICONQUESTION)==IDYES){
fs::path sData=g_sDataDir/"Sites"/clientName;
try{
if(fs::exists(sData)){
fs::remove_all(sData);
}
extDef(sData);
MessageBox(g_hGui,L"Profile has been reset.",L"Success",MB_OK|MB_ICONINFORMATION);
} catch(...){}
UpdateClientsComboBox();
LRESULT selectionIndex=SendMessage(g_hComboClient,CB_FINDSTRINGEXACT,(WPARAM)-1,(LPARAM)clientName.c_str());
if(selectionIndex!=CB_ERR){
SendMessage(g_hComboClient,CB_SETCURSEL,(WPARAM)selectionIndex,0);
}
}
SetUiState(true);
}
void GuiProfUpd(){
SetUiState(false);
wchar_t clientNameBuffer[256];
GetWindowText(g_hComboClient,clientNameBuffer,256);
std::wstring clientName=SanitizeName(clientNameBuffer);
if(clientName.empty()){
MessageBox(g_hGui,L"Please select a client first.",L"Warning",MB_OK|MB_ICONWARNING);
SetUiState(true);
return;
}
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if(g_activeProfiles.count(clientName)){
MessageBox(g_hGui,L"Cannot update a profile that is currently active.",L"Action Denied",MB_OK|MB_ICONWARNING);
SetUiState(true);
return;
}
if(MessageBox(g_hGui,L"This will update/overwrite the profile. Are you sure?",L"Confirm Reset",MB_YESNO|MB_ICONQUESTION)==IDYES){
std::thread([clientName](){
fs::path sData=g_sDataDir/"Sites"/clientName;
try{
if(fs::exists(sData)){
fs::remove_all(sData);
}
extDef(sData);
} catch(...){}
PostMessage(g_hGui,WM_APP_TASK_COMPLETE,0,0);
}).detach();
}
}
void GuiOpenDef(){
SetUiState(false);
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if(g_activeProfiles.count(L"Default")){
MessageBox(g_hGui,L"The Default profile is already open.",L"Already Running",MB_OK|MB_ICONINFORMATION);
SetUiState(true);
return;
}
LaunchProfileAsync(L"Default", false, true);
}
void GuiOpenTmp(){
SetUiState(false);
std::lock_guard<std::mutex> lock(g_activeProfilesMutex);
if(g_activeProfiles.count(L"Temp")){
MessageBox(g_hGui,L"A temporary profile is already open.",L"Already Running",MB_OK|MB_ICONINFORMATION);
SetUiState(true);
return;
}
LaunchProfileAsync(L"Temp", true, false);
}
struct EnumData{
DWORD processId;
std::vector<HWND> windows;
};
BOOL CALLBACK EnumWindowsCallback(HWND hWnd,LPARAM lParam){
EnumData* pData=(EnumData*)lParam;
DWORD processId=0;
GetWindowThreadProcessId(hWnd,&processId);
if(pData->processId==processId&&IsWindowVisible(hWnd)&&GetWindowTextLength(hWnd)>0){
pData->windows.push_back(hWnd);
}
return TRUE;
}
DWORD LaunchProfile(const std::wstring& clientName,bool isTemp,bool isDefault){
fs::path profilePath;
if(isTemp) profilePath=g_sDataDir/"Temp";
else if(isDefault) profilePath=g_sDataDir/"Default";
else profilePath=g_sDataDir/"Sites"/clientName;
if(!fs::exists(profilePath/"ctSpaces")){
if(!extDef(profilePath)){
MessageBox(NULL,L"Error: An error occurred when extracting the profile.",APP_TITLE.c_str(),MB_OK|MB_ICONERROR);
return 0;
}
}
std::wstring cmdLine=std::format(L"\"{}\" --user-data-dir=\"{}\" --no-first-run --disable-sync --disable-features=SyncPromo --edge-skip-compat-layer-relaunch --no-service-autorun",g_sEdgePath.c_str(),profilePath.c_str());
STARTUPINFOW si={sizeof(si)};
PROCESS_INFORMATION pi={};
if(!CreateProcessW(NULL,&cmdLine[0],NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)){
MessageBox(NULL,L"Failed to launch Microsoft Edge.",APP_TITLE.c_str(),MB_OK|MB_ICONERROR);
return 0;
}
CloseHandle(pi.hThread);
return pi.dwProcessId;
}
void UpdateClientsComboBox(){
SendMessage(g_hComboClient,CB_RESETCONTENT,0,0);
fs::path sitesDir=g_sDataDir/"Sites";
if(fs::exists(sitesDir)&&fs::is_directory(sitesDir)){
for(const auto& entry:fs::directory_iterator(sitesDir)){
if(entry.is_directory()){
SendMessage(g_hComboClient,CB_ADDSTRING,0,(LPARAM)entry.path().filename().c_str());
}
}
}
}
std::wstring SanitizeName(const std::wstring& name){
std::wstring sanitized=name;
const std::wstring whitespace=L" \t\n\r\f\v";
sanitized.erase(0,sanitized.find_first_not_of(whitespace));
sanitized.erase(sanitized.find_last_not_of(whitespace)+1);
std::wregex invalidChars(LR"([\\/:*?"<>|])");
sanitized=std::regex_replace(sanitized,invalidChars,L"");
while(!sanitized.empty()&&sanitized.back()==L'.'){
sanitized.pop_back();
}
std::wregex reservedNames(L"^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$",std::regex::icase);
if(std::regex_match(sanitized,reservedNames)){
return L"";
}
return sanitized;
}
bool IsValidFilenameChar(wchar_t c){
const std::wstring invalidChars=L"\\/:*?\"<>|";
return invalidChars.find(c)==std::wstring::npos;
}
bool ExtractResourceToFile(UINT resourceID,const fs::path& destPath){
if(fs::exists(destPath)) return true;
HRSRC hRes=FindResource(g_hInst,MAKEINTRESOURCE(resourceID),L"BINARY");
if(!hRes) return false;
HGLOBAL hResLoad=LoadResource(g_hInst,hRes);
if(!hResLoad) return false;
void* pRes=LockResource(hResLoad);
if(!pRes) return false;
DWORD dwSize=SizeofResource(g_hInst,hRes);
std::ofstream outFile(destPath,std::ios::binary);
if(!outFile) return false;
outFile.write(static_cast<char*>(pRes),dwSize);
return outFile.good();
}
bool RunCommand(const std::wstring& command,const fs::path& workingDir){
fs::path sevenzip=g_sDataDir/L"7za.exe";
std::wstring fullCmd=std::format(L"\"{}\" {}",sevenzip.c_str(),command);
STARTUPINFOW si={sizeof(si)};
PROCESS_INFORMATION pi={};
si.dwFlags=STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWDEFAULT;// SW_SHOW;
if(CreateProcessW(NULL,&fullCmd[0],NULL,NULL,FALSE,0,NULL,workingDir.c_str(),&si,&pi)){
WaitForSingleObject(pi.hProcess,INFINITE);
DWORD exitCode;
GetExitCodeProcess(pi.hProcess,&exitCode);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return exitCode==0;
}
return false;
}
void SetUiState(bool enabled){
EnableWindow(g_hComboClient,enabled);
EnableWindow(g_hBtnGo,enabled);
for(const auto& btn:g_iconButtons){
EnableWindow(btn.hWnd,enabled);
}
if (enabled)
FocusClientEdit();
}
bool extDef(const fs::path& profileDataPath){
fs::create_directories(profileDataPath);
std::wstring cmd=std::format(L"x \"{}\\Default.7z\" -y -o\"{}\"",g_sDataDir.c_str(),profileDataPath.c_str());
if(!RunCommand(cmd,g_sDataDir)){
return false;
}
std::ofstream marker(profileDataPath/"ctSpaces");
marker.close();
return true;
}
void SetWindowAppId(HWND hWnd,const std::wstring& appId){
IPropertyStore* pps;
if(SUCCEEDED(SHGetPropertyStoreForWindow(hWnd,IID_PPV_ARGS(&pps)))){
PROPVARIANT pv;
if(SUCCEEDED(InitPropVariantFromString(appId.c_str(),&pv))){
pps->SetValue(PKEY_AppUserModel_ID,pv);
PropVariantClear(&pv);
}
pps->Release();
}
}
void CleanupProfile(const fs::path& profilePath,const std::vector<std::wstring>& keepList){
std::vector<fs::path> toDelete;
try{
for(const auto& entry:fs::recursive_directory_iterator(profilePath)){
fs::path relativePath=fs::relative(entry.path(),profilePath);
bool shouldKeep=false;
for(const auto& keepItem:keepList){
if(relativePath.wstring().find(keepItem)!=std::wstring::npos){
shouldKeep=true;
break;
}
}
if(!shouldKeep){
toDelete.push_back(entry.path());
}
}
} catch(const fs::filesystem_error&){
}
std::sort(toDelete.rbegin(),toDelete.rend());
for(const auto& path:toDelete){
try{
if(fs::is_regular_file(path)||fs::is_symlink(path)){
fs::remove(path);
} else if(fs::is_directory(path)&&fs::is_empty(path)){
fs::remove(path);
}
} catch(...){ /* ignore errors */ }
}
}
std::wstring AnsiToWide(const std::string& str){
if(str.empty()){
return std::wstring();
}
int size_needed=MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,NULL,0);
if(size_needed==0){
return std::wstring();
}
std::wstring wstrTo(size_needed,0);
MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,&wstrTo[0],size_needed);
if(!wstrTo.empty()&&wstrTo.back()==L'\0'){
wstrTo.pop_back();
}
return wstrTo;
}
std::vector<std::wstring> GetSupportedImageTypes(){
std::vector<std::wstring> supportedTypes;
UINT numDecoders=0,size=0;
Gdiplus::GetImageDecodersSize(&numDecoders,&size);
if(size==0) return supportedTypes;
std::unique_ptr<Gdiplus::ImageCodecInfo[]> pImageCodecInfo(new Gdiplus::ImageCodecInfo[size]);
if(!pImageCodecInfo) return supportedTypes;
Gdiplus::GetImageDecoders(numDecoders,size,pImageCodecInfo.get());
for(UINT i=0; i<numDecoders; ++i){
std::wstring extensions(pImageCodecInfo[i].FilenameExtension);
std::wstringstream ss(extensions);
std::wstring ext;
while(std::getline(ss,ext,L';')){
if(ext.rfind(L"*.",0)==0){
ext=ext.substr(2);
}
std::transform(ext.begin(),ext.end(),ext.begin(),::towlower);
if(ext!=L"ico"&&std::find(supportedTypes.begin(),supportedTypes.end(),ext)==supportedTypes.end()){
supportedTypes.push_back(ext);
}
}
}
return supportedTypes;
}
bool ConvertImageToIcon(const fs::path& sourceImagePath,const fs::path& destIconPath){
std::unique_ptr<Gdiplus::Bitmap> sourceBitmap(Gdiplus::Bitmap::FromFile(sourceImagePath.c_str()));
if(!sourceBitmap||sourceBitmap->GetLastStatus()!=Gdiplus::Ok){
return false;
}
UINT sourceWidth=sourceBitmap->GetWidth();
UINT sourceHeight=sourceBitmap->GetHeight();
int masterSize=max(sourceWidth,sourceHeight);
auto masterScaledBitmap=std::make_unique<Gdiplus::Bitmap>(masterSize,masterSize,PixelFormat32bppARGB);
{
auto graphics=std::make_unique<Gdiplus::Graphics>(masterScaledBitmap.get());
graphics->SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);
graphics->SetPixelOffsetMode(Gdiplus::PixelOffsetModeHighQuality);