-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPrtEasySetup.cpp
More file actions
2994 lines (2608 loc) · 103 KB
/
Copy pathPrtEasySetup.cpp
File metadata and controls
2994 lines (2608 loc) · 103 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
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <commctrl.h>
#include <shellapi.h>
#include <winspool.h>
#include <winsvc.h>
#include <algorithm>
#include <cctype>
#include <cwchar>
#include <cwctype>
#include <filesystem>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <vector>
#ifdef _MSC_VER
#pragma comment(lib, "Advapi32.lib")
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Gdi32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Winspool.lib")
#endif
namespace fs = std::filesystem;
struct Config {
std::wstring mode;
std::wstring portValue;
std::wstring printerName;
std::wstring driverName;
std::wstring infName;
std::wstring flags;
};
struct TextInputDialogState {
std::wstring title;
std::wstring prompt;
std::wstring value;
HWND editHandle = nullptr;
bool accepted = false;
};
struct SelectionDialogState {
std::wstring title;
std::wstring prompt;
std::vector<std::wstring> options;
HWND listHandle = nullptr;
int selectedIndex = -1;
bool accepted = false;
};
fs::path g_baseDir;
fs::path g_logPath;
enum class AppLanguage {
English,
TraditionalChinese
};
struct ProgressWindowState {
HWND windowHandle = nullptr;
HWND labelHandle = nullptr;
HWND progressHandle = nullptr;
bool visible = false;
};
AppLanguage g_appLanguage = AppLanguage::English;
std::wstring g_languageSetting = L"auto";
ProgressWindowState g_progressWindow;
constexpr int kDialogButtonWidth = 88;
constexpr int kDialogButtonHeight = 28;
constexpr int kTextInputWidth = 420;
constexpr int kTextInputHeight = 165;
constexpr int kSelectionWidth = 460;
constexpr int kSelectionHeight = 430;
constexpr int kProgressWidth = 440;
constexpr int kProgressHeight = 145;
constexpr int kAppIconResourceId = 1;
constexpr int kTextPromptId = 1001;
constexpr int kTextEditId = 1002;
constexpr int kListPromptId = 1101;
constexpr int kListBoxId = 1102;
constexpr int kProgressLabelId = 1201;
constexpr int kProgressBarId = 1202;
std::wstring BuildPrinterInfoMessage(const Config& config);
HFONT GetDialogFont();
void CenterWindowOnOwner(HWND handle, HWND owner, int width, int height);
const wchar_t* UiText(const wchar_t* english, const wchar_t* traditionalChinese) {
return g_appLanguage == AppLanguage::TraditionalChinese ? traditionalChinese : english;
}
std::wstring Trim(const std::wstring& value) {
const wchar_t* whitespace = L" \t\r\n";
const auto start = value.find_first_not_of(whitespace);
if (start == std::wstring::npos) {
return L"";
}
const auto end = value.find_last_not_of(whitespace);
return value.substr(start, end - start + 1);
}
std::wstring StripQuotes(std::wstring value) {
value = Trim(value);
if (value.size() >= 2 && value.front() == L'"' && value.back() == L'"') {
return value.substr(1, value.size() - 2);
}
return value;
}
std::wstring ToLowerCopy(std::wstring value) {
std::transform(value.begin(), value.end(), value.begin(), [](wchar_t ch) {
return static_cast<wchar_t>(::towlower(ch));
});
return value;
}
bool IEquals(const std::wstring& left, const std::wstring& right) {
return ToLowerCopy(left) == ToLowerCopy(right);
}
bool StartsWithI(const std::wstring& value, const std::wstring& prefix) {
if (value.size() < prefix.size()) {
return false;
}
return IEquals(value.substr(0, prefix.size()), prefix);
}
bool ContainsI(const std::wstring& value, const std::wstring& needle) {
return ToLowerCopy(value).find(ToLowerCopy(needle)) != std::wstring::npos;
}
std::wstring NormalizeFlags(std::wstring flags) {
flags = Trim(flags);
if (flags.empty()) {
flags = L"000";
}
while (flags.size() < 3) {
flags.push_back(L'0');
}
return flags.substr(0, 3);
}
std::wstring WideFromBytes(const std::string& input, UINT codePage = CP_ACP) {
if (input.empty()) {
return L"";
}
const int size = MultiByteToWideChar(codePage, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
if (size <= 0) {
return L"";
}
std::wstring output(size, L'\0');
MultiByteToWideChar(codePage, 0, input.data(), static_cast<int>(input.size()), output.data(), size);
return output;
}
std::string BytesFromWide(const std::wstring& input, UINT codePage = CP_ACP) {
if (input.empty()) {
return "";
}
const int size = WideCharToMultiByte(codePage, 0, input.c_str(), static_cast<int>(input.size()), nullptr, 0, nullptr, nullptr);
if (size <= 0) {
return "";
}
std::string output(size, '\0');
WideCharToMultiByte(codePage, 0, input.c_str(), static_cast<int>(input.size()), output.data(), size, nullptr, nullptr);
return output;
}
std::wstring ReadTextFile(const fs::path& path) {
std::ifstream input(path, std::ios::binary);
if (!input) {
return L"";
}
std::string bytes((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
if (bytes.size() >= 3 &&
static_cast<unsigned char>(bytes[0]) == 0xEF &&
static_cast<unsigned char>(bytes[1]) == 0xBB &&
static_cast<unsigned char>(bytes[2]) == 0xBF) {
return WideFromBytes(bytes.substr(3), CP_UTF8);
}
if (bytes.size() >= 2) {
const unsigned char b0 = static_cast<unsigned char>(bytes[0]);
const unsigned char b1 = static_cast<unsigned char>(bytes[1]);
if (b0 == 0xFF && b1 == 0xFE) {
const wchar_t* data = reinterpret_cast<const wchar_t*>(bytes.data() + 2);
return std::wstring(data, (bytes.size() - 2) / sizeof(wchar_t));
}
}
return WideFromBytes(bytes, CP_ACP);
}
bool WriteTextFileAcp(const fs::path& path, const std::wstring& text) {
std::ofstream output(path, std::ios::binary | std::ios::trunc);
if (!output) {
return false;
}
const std::string bytes = BytesFromWide(text, CP_ACP);
output.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
return static_cast<bool>(output);
}
std::vector<std::wstring> SplitLines(const std::wstring& text) {
std::vector<std::wstring> lines;
std::wstring current;
for (wchar_t ch : text) {
if (ch == L'\r') {
continue;
}
if (ch == L'\n') {
lines.push_back(current);
current.clear();
} else {
current.push_back(ch);
}
}
if (!current.empty()) {
lines.push_back(current);
}
return lines;
}
std::vector<std::wstring> SplitCsvLine(const std::wstring& line) {
std::vector<std::wstring> parts;
std::wstring current;
for (wchar_t ch : line) {
if (ch == L',') {
parts.push_back(current);
current.clear();
} else {
current.push_back(ch);
}
}
parts.push_back(current);
return parts;
}
std::wstring QuoteArg(const std::wstring& argument) {
if (argument.empty()) {
return L"\"\"";
}
bool needsQuotes = false;
for (wchar_t ch : argument) {
if (iswspace(ch) || ch == L'"') {
needsQuotes = true;
break;
}
}
if (!needsQuotes) {
return argument;
}
std::wstring result = L"\"";
unsigned int backslashes = 0;
for (wchar_t ch : argument) {
if (ch == L'\\') {
++backslashes;
continue;
}
if (ch == L'"') {
result.append(backslashes * 2 + 1, L'\\');
result.push_back(L'"');
backslashes = 0;
continue;
}
result.append(backslashes, L'\\');
backslashes = 0;
result.push_back(ch);
}
result.append(backslashes * 2, L'\\');
result.push_back(L'"');
return result;
}
std::wstring BuildCommandLine(const std::wstring& executable, const std::vector<std::wstring>& args) {
std::wstring commandLine = QuoteArg(executable);
for (const auto& arg : args) {
commandLine.push_back(L' ');
commandLine += QuoteArg(arg);
}
return commandLine;
}
std::wstring GetTimestamp() {
SYSTEMTIME st{};
GetLocalTime(&st);
wchar_t buffer[64] = {};
swprintf_s(buffer, L"%04u-%02u-%02u %02u:%02u:%02u",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buffer;
}
void Log(const std::wstring& message) {
std::wofstream output(g_logPath, std::ios::app);
if (!output) {
return;
}
output << L"[" << GetTimestamp() << L"] " << message << L"\n";
}
std::wstring FormatWin32Error(DWORD errorCode) {
LPWSTR buffer = nullptr;
const DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD length = FormatMessageW(flags, nullptr, errorCode, 0, reinterpret_cast<LPWSTR>(&buffer), 0, nullptr);
std::wstring message = length && buffer ? Trim(buffer) : L"Unknown error";
if (buffer) {
LocalFree(buffer);
}
wchar_t prefix[64] = {};
swprintf_s(prefix, L"0x%08lX (%lu): ", errorCode, errorCode);
return std::wstring(prefix) + message;
}
int ShowMessage(const std::wstring& title, const std::wstring& message, UINT flags) {
return MessageBoxW(nullptr, message.c_str(), title.c_str(), flags | MB_TOPMOST);
}
void ShowErrorWithLog(const std::wstring& title, const std::wstring& message) {
ShowMessage(title, message + L"\n\n" + UiText(L"Log file:", L"\u8A18\u9304\u6A94\uff1A") + L"\n" + g_logPath.wstring(), MB_OK | MB_ICONERROR);
}
bool CanRenderTraditionalChinese() {
HDC dc = GetDC(nullptr);
if (!dc) {
return false;
}
const wchar_t* sample = L"\u5370\u8868\u6A5F\u8A2D\u5B9A";
WORD glyphs[8] = {};
HGDIOBJ oldFont = SelectObject(dc, GetDialogFont());
const DWORD flags = GGI_MARK_NONEXISTING_GLYPHS;
const DWORD count = GetGlyphIndicesW(dc, sample, static_cast<int>(wcslen(sample)), glyphs, flags);
if (oldFont) {
SelectObject(dc, oldFont);
}
ReleaseDC(nullptr, dc);
if (count == GDI_ERROR) {
return false;
}
for (std::size_t i = 0; i < wcslen(sample); ++i) {
if (glyphs[i] == 0xFFFF) {
return false;
}
}
return true;
}
AppLanguage DetectSystemLanguage() {
wchar_t localeName[LOCALE_NAME_MAX_LENGTH] = {};
if (GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH) <= 0) {
return AppLanguage::English;
}
const std::wstring locale = ToLowerCopy(localeName);
if (locale.rfind(L"zh", 0) == 0 && CanRenderTraditionalChinese()) {
return AppLanguage::TraditionalChinese;
}
return AppLanguage::English;
}
std::wstring ReadIniLanguageSetting(const fs::path& path) {
const std::wstring text = ReadTextFile(path);
if (text.empty()) {
return L"auto";
}
for (const auto& rawLine : SplitLines(text)) {
const std::wstring line = Trim(rawLine);
if (line.empty() || StartsWithI(line, L"#") || StartsWithI(line, L";")) {
continue;
}
const auto pos = line.find(L'=');
if (pos == std::wstring::npos) {
continue;
}
const std::wstring key = ToLowerCopy(Trim(line.substr(0, pos)));
const std::wstring value = Trim(line.substr(pos + 1));
if (key == L"lang" || key == L"language" || key == L"ui_lang") {
return value.empty() ? L"auto" : value;
}
}
return L"auto";
}
void ApplyLanguageSetting(const std::wstring& value) {
g_languageSetting = ToLowerCopy(Trim(value));
if (g_languageSetting.empty() || g_languageSetting == L"auto") {
g_appLanguage = DetectSystemLanguage();
return;
}
if (g_languageSetting == L"en" || g_languageSetting == L"en-us" || g_languageSetting == L"english") {
g_appLanguage = AppLanguage::English;
return;
}
if (g_languageSetting == L"zh" ||
g_languageSetting == L"zh-tw" ||
g_languageSetting == L"zh-hk" ||
g_languageSetting == L"zh-mo" ||
g_languageSetting == L"tw" ||
g_languageSetting == L"cht" ||
g_languageSetting == L"traditional") {
g_appLanguage = CanRenderTraditionalChinese() ? AppLanguage::TraditionalChinese : AppLanguage::English;
return;
}
g_appLanguage = DetectSystemLanguage();
}
HFONT GetDialogFont() {
static HFONT font = reinterpret_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT));
return font;
}
HICON GetAppIconLarge() {
static HICON icon = reinterpret_cast<HICON>(
LoadImageW(GetModuleHandleW(nullptr),
MAKEINTRESOURCEW(kAppIconResourceId),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_DEFAULTCOLOR));
return icon ? icon : LoadIconW(nullptr, IDI_APPLICATION);
}
HICON GetAppIconSmall() {
static HICON icon = reinterpret_cast<HICON>(
LoadImageW(GetModuleHandleW(nullptr),
MAKEINTRESOURCEW(kAppIconResourceId),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_DEFAULTCOLOR));
return icon ? icon : LoadIconW(nullptr, IDI_APPLICATION);
}
void SetControlFont(HWND handle) {
if (handle) {
SendMessageW(handle, WM_SETFONT, reinterpret_cast<WPARAM>(GetDialogFont()), TRUE);
}
}
HMENU MenuId(int value) {
return reinterpret_cast<HMENU>(static_cast<INT_PTR>(value));
}
int g_currentProgressPercent = 0;
int g_targetMaxPercent = 0;
std::wstring g_currentProgressMessage;
ULONGLONG g_lastStepTick = 0;
void PumpPendingMessages() {
MSG msg{};
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if (g_progressWindow.visible && g_currentProgressPercent < g_targetMaxPercent) {
ULONGLONG now = GetTickCount64();
if (now - g_lastStepTick >= 1000) {
g_currentProgressPercent++;
g_lastStepTick = now;
if (g_progressWindow.labelHandle) {
std::wstring text = g_currentProgressMessage;
text += L" (" + std::to_wstring(g_currentProgressPercent) + L"%)";
SetWindowTextW(g_progressWindow.labelHandle, text.c_str());
}
if (g_progressWindow.progressHandle) {
SendMessageW(g_progressWindow.progressHandle, PBM_SETPOS, g_currentProgressPercent, 0);
}
}
}
}
bool WaitForHandleWithMessages(HANDLE handle, DWORD timeoutMs, DWORD& waitResult) {
const DWORD startTick = GetTickCount();
for (;;) {
const DWORD elapsed = GetTickCount() - startTick;
if (timeoutMs != INFINITE && elapsed >= timeoutMs) {
waitResult = WAIT_TIMEOUT;
return false;
}
DWORD remaining = INFINITE;
if (timeoutMs != INFINITE) {
remaining = timeoutMs - elapsed;
if (remaining > 50) {
remaining = 50;
}
}
const DWORD result = MsgWaitForMultipleObjects(1, &handle, FALSE, remaining, QS_ALLINPUT);
if (result == WAIT_OBJECT_0) {
waitResult = WAIT_OBJECT_0;
return true;
}
if (result == WAIT_TIMEOUT && timeoutMs != INFINITE) {
continue;
}
if (result == WAIT_OBJECT_0 + 1) {
PumpPendingMessages();
continue;
}
waitResult = result;
return false;
}
}
void SleepWithMessages(DWORD milliseconds) {
const DWORD startTick = GetTickCount();
while ((GetTickCount() - startTick) < milliseconds) {
PumpPendingMessages();
Sleep(20);
}
}
LRESULT CALLBACK ProgressWindowProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CREATE: {
HWND label = CreateWindowExW(
0, L"STATIC", L"",
WS_CHILD | WS_VISIBLE,
14, 16, kProgressWidth - 28, 32,
handle, MenuId(kProgressLabelId), nullptr, nullptr);
SetControlFont(label);
g_progressWindow.labelHandle = label;
HWND progress = CreateWindowExW(
0, PROGRESS_CLASSW, L"",
WS_CHILD | WS_VISIBLE | PBS_SMOOTH,
14, 58, kProgressWidth - 28, 20,
handle, MenuId(kProgressBarId), nullptr, nullptr);
g_progressWindow.progressHandle = progress;
SendMessageW(progress, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
SendMessageW(progress, PBM_SETPOS, 0, 0);
return 0;
}
case WM_CTLCOLORSTATIC: {
HDC hdc = reinterpret_cast<HDC>(wParam);
SetBkMode(hdc, TRANSPARENT);
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE));
}
case WM_CLOSE:
return 0;
default:
break;
}
return DefWindowProcW(handle, message, wParam, lParam);
}
void ShowProgressWindow(const std::wstring& title, const std::wstring& message) {
if (!g_progressWindow.windowHandle) {
INITCOMMONCONTROLSEX icc{};
icc.dwSize = sizeof(icc);
icc.dwICC = ICC_PROGRESS_CLASS;
InitCommonControlsEx(&icc);
static HINSTANCE instance = GetModuleHandleW(nullptr);
WNDCLASSEXW windowClass{};
windowClass.cbSize = sizeof(windowClass);
windowClass.lpfnWndProc = ProgressWindowProc;
windowClass.hInstance = instance;
windowClass.hIcon = GetAppIconLarge();
windowClass.hIconSm = GetAppIconSmall();
windowClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
windowClass.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
windowClass.lpszClassName = L"PrtEasySetupProgressWindow";
RegisterClassExW(&windowClass);
HWND owner = GetActiveWindow();
g_progressWindow.windowHandle = CreateWindowExW(
WS_EX_DLGMODALFRAME,
L"PrtEasySetupProgressWindow",
title.c_str(),
WS_POPUP | WS_CAPTION,
CW_USEDEFAULT, CW_USEDEFAULT, kProgressWidth, kProgressHeight,
owner, nullptr, instance, nullptr);
if (!g_progressWindow.windowHandle) {
return;
}
CenterWindowOnOwner(g_progressWindow.windowHandle, owner, kProgressWidth, kProgressHeight);
ShowWindow(g_progressWindow.windowHandle, SW_SHOW);
UpdateWindow(g_progressWindow.windowHandle);
}
if (g_progressWindow.windowHandle) {
SetWindowTextW(g_progressWindow.windowHandle, title.c_str());
}
if (g_progressWindow.labelHandle) {
SetWindowTextW(g_progressWindow.labelHandle, message.c_str());
}
g_progressWindow.visible = true;
PumpPendingMessages();
}
void UpdateProgressWindow(const std::wstring& message, int percent = -1) {
if (percent >= 0) {
g_currentProgressPercent = percent;
g_lastStepTick = GetTickCount64();
// 根據主要等待步驟設定平滑推進上限,防止卡在 30% 一動不動
if (percent == 10) g_targetMaxPercent = 29; // 準備連接埠:10% -> 29%
else if (percent == 30) g_targetMaxPercent = 69; // 匯入驅動:30% -> 69%
else if (percent == 70) g_targetMaxPercent = 84; // 建立佇列:70% -> 84%
else g_targetMaxPercent = percent;
}
g_currentProgressMessage = message;
if (g_progressWindow.labelHandle) {
std::wstring text = message;
if (g_currentProgressPercent >= 0 && g_currentProgressPercent <= 100) {
text += L" (" + std::to_wstring(g_currentProgressPercent) + L"%)";
}
SetWindowTextW(g_progressWindow.labelHandle, text.c_str());
}
if (g_progressWindow.progressHandle && g_currentProgressPercent >= 0 && g_currentProgressPercent <= 100) {
SendMessageW(g_progressWindow.progressHandle, PBM_SETPOS, g_currentProgressPercent, 0);
}
PumpPendingMessages();
}
void CloseProgressWindow() {
if (g_progressWindow.windowHandle) {
DestroyWindow(g_progressWindow.windowHandle);
}
g_progressWindow.windowHandle = nullptr;
g_progressWindow.labelHandle = nullptr;
g_progressWindow.progressHandle = nullptr;
g_progressWindow.visible = false;
PumpPendingMessages();
}
void CenterWindowOnOwner(HWND handle, HWND owner, int width, int height) {
RECT target{};
if (owner && GetWindowRect(owner, &target)) {
const int x = target.left + ((target.right - target.left) - width) / 2;
const int y = target.top + ((target.bottom - target.top) - height) / 2;
SetWindowPos(handle, nullptr, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
return;
}
RECT workArea{};
SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0);
const int x = workArea.left + ((workArea.right - workArea.left) - width) / 2;
const int y = workArea.top + ((workArea.bottom - workArea.top) - height) / 2;
SetWindowPos(handle, nullptr, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
std::wstring GetWindowTextString(HWND handle) {
const int length = GetWindowTextLengthW(handle);
std::wstring value(static_cast<std::size_t>(length) + 1, L'\0');
GetWindowTextW(handle, value.data(), length + 1);
value.resize(static_cast<std::size_t>(length));
return value;
}
LRESULT CALLBACK TextInputDialogProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
TextInputDialogState* state = reinterpret_cast<TextInputDialogState*>(GetWindowLongPtrW(handle, GWLP_USERDATA));
switch (message) {
case WM_NCCREATE: {
auto* create = reinterpret_cast<CREATESTRUCTW*>(lParam);
SetWindowLongPtrW(handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(create->lpCreateParams));
return TRUE;
}
case WM_CREATE: {
state = reinterpret_cast<TextInputDialogState*>(GetWindowLongPtrW(handle, GWLP_USERDATA));
if (!state) {
return -1;
}
HWND prompt = CreateWindowExW(
0, L"STATIC", state->prompt.c_str(),
WS_CHILD | WS_VISIBLE,
14, 14, kTextInputWidth - 28, 42,
handle, MenuId(kTextPromptId), nullptr, nullptr);
SetControlFont(prompt);
state->editHandle = CreateWindowExW(
WS_EX_CLIENTEDGE, L"EDIT", state->value.c_str(),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
14, 62, kTextInputWidth - 28, 24,
handle, MenuId(kTextEditId), nullptr, nullptr);
SetControlFont(state->editHandle);
HWND okButton = CreateWindowExW(
0, L"BUTTON", UiText(L"OK", L"\u78BA\u5B9A"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
kTextInputWidth - 190, 102, kDialogButtonWidth, kDialogButtonHeight,
handle, MenuId(IDOK), nullptr, nullptr);
SetControlFont(okButton);
HWND cancelButton = CreateWindowExW(
0, L"BUTTON", UiText(L"Cancel", L"\u53D6\u6D88"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP,
kTextInputWidth - 96, 102, kDialogButtonWidth, kDialogButtonHeight,
handle, MenuId(IDCANCEL), nullptr, nullptr);
SetControlFont(cancelButton);
SetFocus(state->editHandle);
SendMessageW(state->editHandle, EM_SETSEL, 0, -1);
return 0;
}
case WM_COMMAND:
if (!state) {
break;
}
switch (LOWORD(wParam)) {
case IDOK:
state->value = Trim(GetWindowTextString(state->editHandle));
state->accepted = true;
DestroyWindow(handle);
return 0;
case IDCANCEL:
state->accepted = false;
DestroyWindow(handle);
return 0;
default:
break;
}
break;
case WM_CTLCOLORSTATIC: {
HDC hdc = reinterpret_cast<HDC>(wParam);
SetBkMode(hdc, TRANSPARENT);
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE));
}
case WM_CLOSE:
if (state) {
state->accepted = false;
}
DestroyWindow(handle);
return 0;
default:
break;
}
return DefWindowProcW(handle, message, wParam, lParam);
}
LRESULT CALLBACK SelectionDialogProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
SelectionDialogState* state = reinterpret_cast<SelectionDialogState*>(GetWindowLongPtrW(handle, GWLP_USERDATA));
switch (message) {
case WM_NCCREATE: {
auto* create = reinterpret_cast<CREATESTRUCTW*>(lParam);
SetWindowLongPtrW(handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(create->lpCreateParams));
return TRUE;
}
case WM_CREATE: {
state = reinterpret_cast<SelectionDialogState*>(GetWindowLongPtrW(handle, GWLP_USERDATA));
if (!state) {
return -1;
}
HWND prompt = CreateWindowExW(
0, L"STATIC", state->prompt.c_str(),
WS_CHILD | WS_VISIBLE,
14, 14, kSelectionWidth - 28, 36,
handle, MenuId(kListPromptId), nullptr, nullptr);
SetControlFont(prompt);
state->listHandle = CreateWindowExW(
WS_EX_CLIENTEDGE, L"LISTBOX", L"",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY,
14, 52, kSelectionWidth - 28, 292,
handle, MenuId(kListBoxId), nullptr, nullptr);
SetControlFont(state->listHandle);
for (const auto& option : state->options) {
SendMessageW(state->listHandle, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(option.c_str()));
}
if (!state->options.empty()) {
SendMessageW(state->listHandle, LB_SETCURSEL, 0, 0);
}
HWND okButton = CreateWindowExW(
0, L"BUTTON", UiText(L"OK", L"\u78BA\u5B9A"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
kSelectionWidth - 190, 358, kDialogButtonWidth, kDialogButtonHeight,
handle, MenuId(IDOK), nullptr, nullptr);
SetControlFont(okButton);
HWND cancelButton = CreateWindowExW(
0, L"BUTTON", UiText(L"Cancel", L"\u53D6\u6D88"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP,
kSelectionWidth - 96, 358, kDialogButtonWidth, kDialogButtonHeight,
handle, MenuId(IDCANCEL), nullptr, nullptr);
SetControlFont(cancelButton);
SetFocus(state->listHandle);
return 0;
}
case WM_COMMAND:
if (!state) {
break;
}
if (LOWORD(wParam) == kListBoxId && HIWORD(wParam) == LBN_DBLCLK) {
SendMessageW(handle, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), 0);
return 0;
}
switch (LOWORD(wParam)) {
case IDOK: {
const int selected = static_cast<int>(SendMessageW(state->listHandle, LB_GETCURSEL, 0, 0));
if (selected == LB_ERR) {
MessageBoxW(handle, UiText(L"Please select an item first.", L"\u8ACB\u5148\u9078\u64C7\u4E00\u500B\u9805\u76EE\u3002"), state->title.c_str(), MB_OK | MB_ICONINFORMATION | MB_TOPMOST);
return 0;
}
state->selectedIndex = selected;
state->accepted = true;
DestroyWindow(handle);
return 0;
}
case IDCANCEL:
state->accepted = false;
DestroyWindow(handle);
return 0;
default:
break;
}
break;
case WM_CTLCOLORSTATIC: {
HDC hdc = reinterpret_cast<HDC>(wParam);
SetBkMode(hdc, TRANSPARENT);
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE));
}
case WM_CLOSE:
if (state) {
state->accepted = false;
}
DestroyWindow(handle);
return 0;
default:
break;
}
return DefWindowProcW(handle, message, wParam, lParam);
}
template <typename TState>
bool RunModalWindow(const wchar_t* className,
WNDPROC procedure,
TState& state,
int width,
int height,
HWND* createdHandle = nullptr) {
static HINSTANCE instance = GetModuleHandleW(nullptr);
WNDCLASSEXW windowClass{};
windowClass.cbSize = sizeof(windowClass);
windowClass.lpfnWndProc = procedure;
windowClass.hInstance = instance;
windowClass.hIcon = GetAppIconLarge();
windowClass.hIconSm = GetAppIconSmall();
windowClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
windowClass.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
windowClass.lpszClassName = className;
RegisterClassExW(&windowClass);
HWND owner = GetActiveWindow();
HWND handle = CreateWindowExW(
WS_EX_DLGMODALFRAME | WS_EX_CONTROLPARENT,
className,
state.title.c_str(),
WS_POPUP | WS_CAPTION | WS_SYSMENU,
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
owner, nullptr, instance, &state);
if (!handle) {
return false;
}
if (createdHandle) {
*createdHandle = handle;
}
CenterWindowOnOwner(handle, owner, width, height);
if (owner) {
EnableWindow(owner, FALSE);
}
ShowWindow(handle, SW_SHOW);
UpdateWindow(handle);
MSG msg{};
while (IsWindow(handle) && GetMessageW(&msg, nullptr, 0, 0) > 0) {
if (!IsDialogMessageW(handle, &msg)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
if (owner) {
EnableWindow(owner, TRUE);
SetActiveWindow(owner);
}
return state.accepted;
}
bool ShowTextInputDialog(const std::wstring& title,
const std::wstring& prompt,
const std::wstring& defaultValue,
std::wstring& value) {
TextInputDialogState state;
state.title = title;
state.prompt = prompt;
state.value = defaultValue;
if (!RunModalWindow(L"PrtEasySetupTextInputDialog", TextInputDialogProc, state, kTextInputWidth, kTextInputHeight)) {
return false;
}
value = state.value;
return true;
}
bool ShowSelectionDialog(const std::wstring& title,
const std::wstring& prompt,
const std::vector<std::wstring>& options,
std::wstring& value) {
if (options.empty()) {
return false;
}
SelectionDialogState state;
state.title = title;
state.prompt = prompt;
state.options = options;
if (!RunModalWindow(L"PrtEasySetupSelectionDialog", SelectionDialogProc, state, kSelectionWidth, kSelectionHeight)) {
return false;
}
if (state.selectedIndex < 0 || state.selectedIndex >= static_cast<int>(state.options.size())) {
return false;
}
value = state.options[static_cast<std::size_t>(state.selectedIndex)];
return true;
}
bool RunProcess(const std::wstring& executable, const std::vector<std::wstring>& args, DWORD& exitCode, DWORD timeoutMs = 120000) {
std::wstring commandLine = BuildCommandLine(executable, args);
std::vector<wchar_t> mutableCommandLine(commandLine.begin(), commandLine.end());
mutableCommandLine.push_back(L'\0');
STARTUPINFOW si{};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi{};
Log(L"Run: " + commandLine);
const BOOL created = CreateProcessW(
nullptr,
mutableCommandLine.data(),
nullptr,
nullptr,
FALSE,
CREATE_NO_WINDOW,
nullptr,
g_baseDir.c_str(),
&si,
&pi);
if (!created) {