-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrtEasyBAK.cpp
More file actions
4894 lines (4289 loc) · 165 KB
/
Copy pathPrtEasyBAK.cpp
File metadata and controls
4894 lines (4289 loc) · 165 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 <richedit.h>
#include <shellapi.h>
#include <wincrypt.h>
#include <winspool.h>
#include <winsvc.h>
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cwctype>
#include <exception>
#include <filesystem>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#ifdef _MSC_VER
#pragma comment(lib, "Advapi32.lib")
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Crypt32.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;
enum class AppLanguage {
English,
TraditionalChinese
};
struct ProgressWindowState {
HWND windowHandle = nullptr;
HWND labelHandle = nullptr;
HWND detailHandle = nullptr;
HWND progressHandle = nullptr;
int maximum = 0;
};
struct SelectionDialogState {
std::wstring title;
std::wstring prompt;
std::vector<std::wstring> options;
HWND listHandle = nullptr;
int selectedIndex = -1;
bool accepted = false;
};
enum class AppAction {
Cancel = 0,
Backup = 1,
Restore = 2
};
struct ActionDialogState {
std::wstring title;
std::wstring prompt;
AppAction action = AppAction::Cancel;
bool accepted = false;
};
struct AboutDialogState {
std::wstring title;
std::wstring content;
HWND textHandle = nullptr;
bool accepted = false;
};
struct CheckListItem {
std::wstring name;
std::wstring detail;
std::wstring port;
bool checked = true;
};
struct CheckListDialogState {
std::wstring title;
std::wstring prompt;
std::wstring description;
std::vector<CheckListItem> items;
HWND listHandle = nullptr;
HWND countHandle = nullptr;
bool accepted = false;
std::vector<int> selectedIndices;
};
struct DriverBackupInfo {
std::wstring name;
std::wstring relativeInfPath;
std::wstring relativeFolder;
};
struct PortInfo {
std::wstring name;
std::wstring kind;
std::wstring printerHostAddress;
std::wstring queueName;
std::uint32_t portNumber = 0;
bool snmpEnabled = false;
std::uint32_t snmpIndex = 0;
std::wstring snmpCommunity;
std::wstring protocol;
bool lprByteCounting = false;
std::wstring portMonitor;
};
struct NativePrinterRecord {
std::wstring name;
std::wstring serverName;
std::wstring shareName;
std::wstring driverName;
std::wstring portName;
std::wstring comment;
std::wstring location;
std::wstring datatype;
std::wstring printProcessor;
DWORD attributes = 0;
};
struct PrinterEntry {
std::wstring name;
std::wstring driverName;
std::wstring portName;
bool shared = false;
std::wstring shareName;
std::wstring comment;
std::wstring location;
std::wstring datatype;
std::wstring printProcessor;
bool published = false;
bool keepPrintedJobs = false;
bool isDefault = false;
bool isConnectionPrinter = false;
std::wstring connectionName;
std::wstring usbPnpKey;
DriverBackupInfo driver;
PortInfo port;
};
struct DriverRestoreMaterial {
std::wstring requestedName;
fs::path stagedFolder;
std::vector<fs::path> infFiles;
std::wstring resolvedName;
bool prepared = false;
};
constexpr int kProgressWidth = 480;
constexpr int kProgressHeight = 194;
constexpr int kActionWidth = 600;
constexpr int kActionHeight = 280;
constexpr int kSelectionWidth = 560;
constexpr int kSelectionHeight = 458;
constexpr int kCheckListWidth = 980;
constexpr int kCheckListHeight = 682;
constexpr int kAboutWidth = 720;
constexpr int kAboutHeight = 560;
constexpr int kDialogButtonWidth = 112;
constexpr int kDialogButtonHeight = 34;
constexpr int kAppIconResourceId = 1;
constexpr int kActionPromptId = 1251;
constexpr int kActionAboutId = 1252;
constexpr int kActionLangComboId = 1253;
constexpr int kProgressLabelId = 1201;
constexpr int kProgressDetailId = 1203;
constexpr int kProgressBarId = 1202;
constexpr int kListPromptId = 1301;
constexpr int kListBoxId = 1302;
constexpr int kCheckPromptId = 1401;
constexpr int kCheckDescriptionId = 1402;
constexpr int kCheckCountId = 1403;
constexpr int kCheckListViewId = 1404;
constexpr int kCheckSelectAllId = 1405;
constexpr int kCheckClearId = 1406;
constexpr int kAboutTextId = 1501;
void ShowAboutDialog();
fs::path g_baseDir;
fs::path g_backupRoot;
fs::path g_driversRoot;
fs::path g_printersRoot;
fs::path g_configPath;
fs::path g_logPath;
fs::path g_tempRoot;
ProgressWindowState g_progressWindow;
AppLanguage g_appLanguage = AppLanguage::English;
std::wstring g_languageSetting = L"auto";
std::wstring g_uiFontFace = L"Segoe UI";
HFONT g_dialogFont = nullptr;
HFONT g_dialogBoldFont = nullptr;
HBRUSH g_dialogBackgroundBrush = nullptr;
HBRUSH g_panelBackgroundBrush = nullptr;
HBRUSH g_listBackgroundBrush = nullptr;
constexpr COLORREF kColorDialogBackground = RGB(241, 245, 250);
constexpr COLORREF kColorPanelBackground = RGB(230, 237, 246);
constexpr COLORREF kColorListBackground = RGB(252, 253, 255);
constexpr COLORREF kColorTextPrimary = RGB(25, 43, 63);
constexpr COLORREF kColorTextSecondary = RGB(84, 103, 124);
constexpr COLORREF kColorAccent = RGB(29, 116, 217);
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 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 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(static_cast<std::size_t>(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.data(), static_cast<int>(input.size()), nullptr, 0, nullptr, nullptr);
if (size <= 0) {
return "";
}
std::string output(static_cast<std::size_t>(size), '\0');
WideCharToMultiByte(codePage, 0, input.data(), 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_UTF8);
}
bool WriteUtf8File(const fs::path& path, const std::wstring& text) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
std::ofstream output(path, std::ios::binary | std::ios::trunc);
if (!output) {
return false;
}
const std::string bytes = BytesFromWide(text, CP_UTF8);
output.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
return static_cast<bool>(output);
}
void AppendUtf8Line(const fs::path& path, const std::wstring& line) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
std::ofstream output(path, std::ios::binary | std::ios::app);
if (!output) {
return;
}
const std::string bytes = BytesFromWide(line + L"\r\n", CP_UTF8);
output.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
}
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::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(buffer, 64, L"%04u-%02u-%02u %02u:%02u:%02u",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buffer;
}
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(prefix, 64, L"0x%08lX (%lu): ", errorCode, errorCode);
return std::wstring(prefix) + message;
}
void Log(const std::wstring& message) {
(void)message;
}
std::wstring JoinLines(const std::vector<std::wstring>& lines) {
std::wstring result;
for (std::size_t i = 0; i < lines.size(); ++i) {
if (i > 0) {
result += L"\r\n";
}
result += lines[i];
}
return result;
}
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, MB_OK | MB_ICONERROR);
}
UINT GetUiDpi() {
static UINT dpi = 0;
if (!dpi) {
HDC screen = GetDC(nullptr);
dpi = screen ? static_cast<UINT>(GetDeviceCaps(screen, LOGPIXELSY)) : 96;
if (screen) {
ReleaseDC(nullptr, screen);
}
if (!dpi) {
dpi = 96;
}
}
return dpi;
}
int ScaleUi(int value) {
return MulDiv(value, static_cast<int>(GetUiDpi()), 96);
}
HFONT GetDialogFont(bool bold = false) {
if (!g_dialogFont) {
const int dpi = static_cast<int>(GetUiDpi());
g_dialogFont = CreateFontW(
-MulDiv(11, dpi, 72),
0,
0,
0,
FW_NORMAL,
FALSE,
FALSE,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
g_uiFontFace.c_str());
g_dialogBoldFont = CreateFontW(
-MulDiv(12, dpi, 72),
0,
0,
0,
FW_SEMIBOLD,
FALSE,
FALSE,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
g_uiFontFace.c_str());
}
return bold && g_dialogBoldFont ? g_dialogBoldFont : g_dialogFont;
}
void SetControlFont(HWND handle, bool bold = false) {
if (handle) {
SendMessageW(handle, WM_SETFONT, reinterpret_cast<WPARAM>(GetDialogFont(bold)), TRUE);
}
}
const wchar_t* UiText(const wchar_t* english, const wchar_t* traditionalChinese) {
return g_appLanguage == AppLanguage::TraditionalChinese ? traditionalChinese : english;
}
bool EnsureRichEditLoaded() {
static HMODULE richEditModule = LoadLibraryW(L"Msftedit.dll");
return richEditModule != nullptr;
}
std::wstring GetControlTextRange(HWND handle, LONG start, LONG end) {
if (!handle || start < 0 || end <= start) {
return L"";
}
std::vector<wchar_t> buffer(static_cast<std::size_t>(end - start + 1), L'\0');
TEXTRANGEW textRange{};
textRange.chrg.cpMin = start;
textRange.chrg.cpMax = end;
textRange.lpstrText = buffer.data();
const LRESULT copied = SendMessageW(handle, EM_GETTEXTRANGE, 0, reinterpret_cast<LPARAM>(&textRange));
if (copied <= 0) {
return L"";
}
return std::wstring(buffer.data(), static_cast<std::size_t>(copied));
}
bool OpenExternalUrl(const std::wstring& url) {
if (url.empty()) {
return false;
}
const HINSTANCE instance = ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
return reinterpret_cast<INT_PTR>(instance) > 32;
}
std::wstring BuildAboutText() {
if (g_appLanguage == AppLanguage::TraditionalChinese) {
return JoinLines({
L"Windows Printer Backup Restore",
L"Windows 印表機備份與還原工具",
L"",
L"版本:v1.2.0.0",
L"作者:Terence0816",
L"授權:MIT License",
L"GitHub:",
L"https://github.com/Terence0816/Windows-Printer-Backup-Restore",
L"",
L"Windows Printer Backup Restore 是一套輕量化的 Windows 印表機備份與還原工具,適合 IT 管理員、系統維護人員、MSP 維護商,以及需要將印表機設定從一台電腦移轉到另一台電腦的使用者。",
L"",
L"本工具可協助備份本機已安裝的實體印表機,並盡可能在另一台 Windows 電腦上自動還原印表機、驅動程式、連接埠、列印偏好設定與預設印表機資訊。",
L"",
L"主要功能:",
L"* 備份本機實體印表機",
L"* 還原印表機到另一台 Windows 電腦",
L"* 備份與還原印表機驅動程式",
L"* 支援 TCP/IP、USB、Local Port、LPR Port 連接埠資訊",
L"* 支援印表機偏好設定匯出與匯入",
L"* 可記錄並還原原本的預設印表機",
L"* 還原前可勾選要還原的印表機",
L"* 還原清單可顯示印表機名稱、型號 / 驅動、連接埠",
L"* 共享印表機支援原始連接、Local Port、LPR Port 三種還原模式",
L"* 自動略過常見虛擬印表機",
L"* 支援繁體中文與英文介面",
L"* 可從網路分享路徑執行",
L"* 提供可攜式 EXE 執行檔",
L"",
L"執行需求:",
L"請使用系統管理員身分執行本程式。",
L"",
L"備份資料夾:",
L"PrinterBackup",
L"",
L"注意事項:",
L"* 部分印表機設定可能會受到驅動程式版本與 Windows 版本影響。",
L"* USB 印表機還原後,可能仍需要重新插拔或手動確認 USB 連接埠。",
L"* 網路共用印表機可能需要原始列印伺服器仍可連線。",
L"* 建議正式大量還原前,先於目標環境進行測試。",
L"",
L"問題回報 / 建議:",
L"請至 GitHub Issues 回報問題或提出建議。",
L"",
L"免責聲明:",
L"本工具依現況提供,作者不保證所有印表機、驅動程式與 Windows 環境皆能完整還原。"
});
}
return JoinLines({
L"Windows Printer Backup Restore",
L"Windows Printer Backup and Restore Utility",
L"",
L"Version: v1.2.0.0",
L"Author: Terence0816",
L"License: MIT License",
L"GitHub:",
L"https://github.com/Terence0816/Windows-Printer-Backup-Restore",
L"",
L"Windows Printer Backup Restore is a lightweight utility for backing up and restoring Windows printers. It is designed for IT administrators, support engineers, MSP service providers, and users who need to migrate printer settings from one Windows computer to another.",
L"",
L"This tool helps back up local physical printers and restore printers, drivers, ports, printer preferences, and the original default printer on another Windows PC as automatically as possible.",
L"",
L"Main Features:",
L"* Backup local physical printers",
L"* Restore printers on another Windows PC",
L"* Backup and restore printer drivers",
L"* Support TCP/IP, USB, Local Port, and LPR Port information",
L"* Export and import printer preferences",
L"* Record and restore the original default printer when possible",
L"* Select which printers to restore before starting",
L"* Display printer name, model / driver, and port information",
L"* Support three restore modes for shared printers: Original Connection, Local Port, and LPR Port",
L"* Skip common virtual printers automatically",
L"* Traditional Chinese and English interface support",
L"* Network-path friendly execution",
L"* Portable EXE design",
L"",
L"Required Permission:",
L"Please run this program as Administrator.",
L"",
L"Backup Folder:",
L"PrinterBackup",
L"",
L"Notes:",
L"* Some printer preferences may depend on the printer driver version and Windows version.",
L"* USB printers may still need to be reconnected or manually confirmed after restore.",
L"* Network shared printers may require the original print server to remain available.",
L"* Please test in your own environment before large-scale deployment.",
L"",
L"Support / Feedback:",
L"Please report issues or suggestions through GitHub Issues.",
L"",
L"Disclaimer:",
L"This software is provided as-is. The author does not guarantee full compatibility with every printer, driver, or Windows environment."
});
}
void ResetDialogFonts() {
if (g_dialogFont) {
DeleteObject(g_dialogFont);
g_dialogFont = nullptr;
}
if (g_dialogBoldFont) {
DeleteObject(g_dialogBoldFont);
g_dialogBoldFont = nullptr;
}
}
bool CanFontRenderText(const wchar_t* faceName, const wchar_t* sample) {
HDC dc = GetDC(nullptr);
if (!dc) {
return false;
}
HFONT font = CreateFontW(
-MulDiv(10, GetDeviceCaps(dc, LOGPIXELSY), 72),
0,
0,
0,
FW_NORMAL,
FALSE,
FALSE,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
faceName);
if (!font) {
ReleaseDC(nullptr, dc);
return false;
}
WORD glyphs[32] = {};
HGDIOBJ oldFont = SelectObject(dc, font);
const int length = static_cast<int>(wcslen(sample));
const DWORD result = GetGlyphIndicesW(dc, sample, length, glyphs, GGI_MARK_NONEXISTING_GLYPHS);
if (oldFont) {
SelectObject(dc, oldFont);
}
DeleteObject(font);
ReleaseDC(nullptr, dc);
if (result == GDI_ERROR) {
return false;
}
for (int i = 0; i < length; ++i) {
if (glyphs[i] == 0xFFFF) {
return false;
}
}
return true;
}
bool CanRenderTraditionalChinese() {
const wchar_t* sample = L"\u5099\u4efd\u9084\u539f\u5370\u8868\u6a5f";
const wchar_t* candidates[] = {
L"Microsoft JhengHei UI",
L"Microsoft JhengHei",
L"PMingLiU",
L"MingLiU",
L"Segoe UI"
};
for (const auto* candidate : candidates) {
if (CanFontRenderText(candidate, sample)) {
g_uiFontFace = candidate;
return true;
}
}
return false;
}
AppLanguage DetectSystemLanguage() {
wchar_t localeName[LOCALE_NAME_MAX_LENGTH] = {};
if (GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH) <= 0) {
g_uiFontFace = L"Segoe UI";
return AppLanguage::English;
}
const std::wstring locale = ToLowerCopy(localeName);
if (locale.rfind(L"zh", 0) == 0 && CanRenderTraditionalChinese()) {
return AppLanguage::TraditionalChinese;
}
g_uiFontFace = L"Segoe UI";
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 EnsureConfigIniExists() {
std::error_code ec;
if (fs::exists(g_configPath, ec)) {
return;
}
const std::wstring content =
L"; PrtEasyBAK settings\r\n"
L"; ui_lang examples / 語系範例\r\n"
L"; ui_lang=auto ; Auto detect. Chinese systems prefer Traditional Chinese when it can be rendered.\r\n"
L"; ui_lang=zh-TW ; Force Traditional Chinese / 強制繁體中文\r\n"
L"; ui_lang=en ; Force English / 強制英文\r\n"
L"ui_lang=auto\r\n";
WriteUtf8File(g_configPath, content);
}
void ApplyLanguageSetting(const std::wstring& value) {
g_languageSetting = ToLowerCopy(Trim(value));
g_uiFontFace = L"Segoe UI";
if (g_languageSetting.empty() || g_languageSetting == L"auto") {
g_appLanguage = DetectSystemLanguage();
ResetDialogFonts();
return;
}
if (g_languageSetting == L"en" ||
g_languageSetting == L"en-us" ||
g_languageSetting == L"english") {
g_appLanguage = AppLanguage::English;
ResetDialogFonts();
return;
}
if (g_languageSetting == L"zh" ||
g_languageSetting == L"zh-tw" ||
g_languageSetting == L"zh-hant" ||
g_languageSetting == L"zh-hk" ||
g_languageSetting == L"tw" ||
g_languageSetting == L"cht" ||
g_languageSetting == L"traditional") {
g_appLanguage = CanRenderTraditionalChinese() ? AppLanguage::TraditionalChinese : AppLanguage::English;
if (g_appLanguage == AppLanguage::English) {
g_uiFontFace = L"Segoe UI";
}
ResetDialogFonts();
return;
}
g_appLanguage = DetectSystemLanguage();
ResetDialogFonts();
}
HBRUSH GetDialogBackgroundBrush() {
if (!g_dialogBackgroundBrush) {
g_dialogBackgroundBrush = CreateSolidBrush(kColorDialogBackground);
}
return g_dialogBackgroundBrush;
}
HBRUSH GetPanelBackgroundBrush() {
if (!g_panelBackgroundBrush) {
g_panelBackgroundBrush = CreateSolidBrush(kColorPanelBackground);
}
return g_panelBackgroundBrush;
}
HBRUSH GetListBackgroundBrush() {
if (!g_listBackgroundBrush) {
g_listBackgroundBrush = CreateSolidBrush(kColorListBackground);
}
return g_listBackgroundBrush;
}
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 ApplyWindowIcons(HWND handle) {
if (!handle) {
return;
}
SendMessageW(handle, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(GetAppIconLarge()));
SendMessageW(handle, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(GetAppIconSmall()));
}
void ApplyListViewTheme(HWND handle) {
if (!handle) {
return;
}
ListView_SetBkColor(handle, kColorListBackground);
ListView_SetTextBkColor(handle, kColorListBackground);
ListView_SetTextColor(handle, kColorTextPrimary);
}
INT_PTR HandleDialogControlColor(UINT message, WPARAM wParam, LPARAM lParam) {
HDC dc = reinterpret_cast<HDC>(wParam);
HWND control = reinterpret_cast<HWND>(lParam);
if (message == WM_CTLCOLORDLG) {
return reinterpret_cast<INT_PTR>(GetDialogBackgroundBrush());
}
if (message == WM_CTLCOLORSTATIC) {
SetBkMode(dc, TRANSPARENT);
COLORREF textColor = kColorTextPrimary;
const int controlId = GetDlgCtrlID(control);
if (controlId == kCheckDescriptionId || controlId == kProgressDetailId) {
textColor = kColorTextSecondary;
} else if (controlId == kCheckCountId) {
textColor = kColorAccent;
}
SetTextColor(dc, textColor);
return reinterpret_cast<INT_PTR>(GetDialogBackgroundBrush());
}
if (message == WM_CTLCOLORLISTBOX) {
SetBkColor(dc, kColorListBackground);
SetTextColor(dc, kColorTextPrimary);
return reinterpret_cast<INT_PTR>(GetListBackgroundBrush());
}
if (message == WM_CTLCOLOREDIT) {
SetBkColor(dc, kColorListBackground);
SetTextColor(dc, kColorTextPrimary);
return reinterpret_cast<INT_PTR>(GetListBackgroundBrush());
}
return 0;
}
void InitUiCommonControls() {
static bool initialized = false;
if (initialized) {
return;
}
INITCOMMONCONTROLSEX icc{};
icc.dwSize = sizeof(icc);
icc.dwICC = ICC_PROGRESS_CLASS | ICC_LISTVIEW_CLASSES;
InitCommonControlsEx(&icc);
initialized = true;
}
HMENU MenuId(int value) {
return reinterpret_cast<HMENU>(static_cast<INT_PTR>(value));
}
void PumpPendingMessages() {
MSG msg{};
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
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);
}
}
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;