-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cpp
More file actions
3668 lines (3518 loc) · 211 KB
/
Copy pathMainWindow.xaml.cpp
File metadata and controls
3668 lines (3518 loc) · 211 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
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
#include <shlobj.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <sstream>
namespace winrt
{
using namespace Windows::ApplicationModel::DataTransfer;
using namespace Windows::Foundation;
using namespace Windows::Storage::Pickers;
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::UI::Xaml::Controls;
using namespace Microsoft::UI::Xaml::Media;
}
namespace
{
constexpr int kIconResource = 201;
constexpr wchar_t kSettingsKey[] = L"Software\\CodeAlexandrov\\CryptoProCleanup\\ModernWinUI";
std::wstring gRuntimeThemeKey = L"Light";
bool ReadSettingDword(wchar_t const* name, DWORD* value)
{
DWORD size = sizeof(*value), type = 0;
return RegGetValueW(HKEY_CURRENT_USER, kSettingsKey, name, RRF_RT_REG_DWORD,
&type, value, &size) == ERROR_SUCCESS;
}
std::wstring ReadSettingString(wchar_t const* name)
{
DWORD size = 0;
if (RegGetValueW(HKEY_CURRENT_USER, kSettingsKey, name, RRF_RT_REG_SZ,
nullptr, nullptr, &size) != ERROR_SUCCESS || size < sizeof(wchar_t)) return {};
std::wstring value(size / sizeof(wchar_t), L'\0');
if (RegGetValueW(HKEY_CURRENT_USER, kSettingsKey, name, RRF_RT_REG_SZ,
nullptr, value.data(), &size) != ERROR_SUCCESS) return {};
while (!value.empty() && value.back() == L'\0') value.pop_back();
return value;
}
void WriteSettingDword(HKEY key, wchar_t const* name, DWORD value)
{
RegSetValueExW(key, name, 0, REG_DWORD, reinterpret_cast<BYTE const*>(&value), sizeof(value));
}
void WriteSettingString(HKEY key, wchar_t const* name, std::wstring const& value)
{
RegSetValueExW(key, name, 0, REG_SZ, reinterpret_cast<BYTE const*>(value.c_str()),
static_cast<DWORD>((value.size() + 1) * sizeof(wchar_t)));
}
winrt::TextBlock Text(std::wstring const& value, double size = 12.0)
{
winrt::TextBlock text;
text.Text(value);
text.FontSize(size);
text.TextWrapping(winrt::TextWrapping::Wrap);
return text;
}
winrt::ColumnDefinition Column(double value, winrt::GridUnitType unit)
{
winrt::ColumnDefinition column;
column.Width(winrt::GridLength{value, unit});
return column;
}
winrt::Brush ThemeBrush(wchar_t const* key)
{
auto resources = winrt::Application::Current().Resources();
auto themes = resources.ThemeDictionaries();
auto themeKey = winrt::box_value(gRuntimeThemeKey);
if (themes.HasKey(themeKey))
{
auto dictionary = themes.Lookup(themeKey).as<winrt::ResourceDictionary>();
auto resourceKey = winrt::box_value(key);
if (dictionary.HasKey(resourceKey)) return dictionary.Lookup(resourceKey).as<winrt::Brush>();
}
return resources.Lookup(winrt::box_value(key)).as<winrt::Brush>();
}
winrt::Border PaddedDialogContent(winrt::UIElement const& child)
{
winrt::Border host;
auto resources = winrt::Application::Current().Resources();
host.Padding(winrt::unbox_value<winrt::Thickness>(
resources.Lookup(winrt::box_value(L"DialogContentPadding"))));
host.Child(child);
return host;
}
enum class BadgeTone { Neutral, Success, Warning, Danger };
void ApplyBadgeTheme(winrt::Border const& badge, BadgeTone tone)
{
wchar_t const* background = tone == BadgeTone::Success ? L"BadgeSuccessBackgroundBrush" :
tone == BadgeTone::Warning ? L"BadgeWarningBackgroundBrush" :
tone == BadgeTone::Danger ? L"BadgeDangerBackgroundBrush" : L"BadgeNeutralBackgroundBrush";
wchar_t const* foreground = tone == BadgeTone::Success ? L"BadgeSuccessForegroundBrush" :
tone == BadgeTone::Warning ? L"BadgeWarningForegroundBrush" :
tone == BadgeTone::Danger ? L"BadgeDangerForegroundBrush" : L"BadgeNeutralForegroundBrush";
badge.Background(ThemeBrush(background));
badge.BorderBrush(ThemeBrush(tone == BadgeTone::Danger ? L"DangerBorderBrush" :
tone == BadgeTone::Warning ? L"WarningBorderBrush" : L"SubtleBorderBrush"));
if (auto label = badge.Child().try_as<winrt::TextBlock>()) label.Foreground(ThemeBrush(foreground));
}
winrt::Border Badge(std::wstring const& value, BadgeTone tone)
{
winrt::Border badge;
badge.HorizontalAlignment(winrt::HorizontalAlignment::Left);
badge.Padding(winrt::Thickness{9, 5, 9, 5});
badge.CornerRadius(winrt::CornerRadius{8});
badge.BorderThickness(winrt::Thickness{1});
badge.Tag(winrt::box_value(static_cast<int32_t>(tone)));
auto label = Text(value, 10);
badge.Child(label);
ApplyBadgeTheme(badge, tone);
return badge;
}
void RefreshBadgeThemes(winrt::DependencyObject const& root)
{
if (!root) return;
if (auto border = root.try_as<winrt::Border>())
{
const int32_t tone = winrt::unbox_value_or<int32_t>(border.Tag(), -1);
if (tone >= static_cast<int32_t>(BadgeTone::Neutral) &&
tone <= static_cast<int32_t>(BadgeTone::Danger))
ApplyBadgeTheme(border, static_cast<BadgeTone>(tone));
}
const int children = winrt::VisualTreeHelper::GetChildrenCount(root);
for (int index = 0; index < children; ++index)
RefreshBadgeThemes(winrt::VisualTreeHelper::GetChild(root, index));
}
std::wstring FormatByteCount(unsigned long long bytes)
{
constexpr unsigned long long mib = 1024ull * 1024;
constexpr unsigned long long gib = 1024ull * mib;
wchar_t buffer[64]{};
if (bytes >= gib) swprintf_s(buffer, L"%.1f GB", static_cast<double>(bytes) / gib);
else swprintf_s(buffer, L"%llu MB", (bytes + mib - 1) / mib);
return buffer;
}
std::wstring ParentDirectory(std::wstring path)
{
if (path.empty()) return {};
std::vector<wchar_t> buffer(path.begin(), path.end());
buffer.push_back(L'\0');
if (PathRemoveFileSpecW(buffer.data())) return buffer.data();
return path;
}
std::wstring NormalizeUiPath(std::wstring path)
{
path = cpc::Trim(path);
std::replace(path.begin(), path.end(), L'/', L'\\');
while (path.size() > 3 && path.back() == L'\\') path.pop_back();
return cpc::ToLower(path);
}
std::wstring VolumeRootOf(std::wstring const& path)
{
std::array<wchar_t, MAX_PATH> root{};
return GetVolumePathNameW(path.c_str(), root.data(), static_cast<DWORD>(root.size())) ? root.data() : L"";
}
}
namespace winrt::CryptoProCleanupModern::implementation
{
MainWindow::MainWindow()
{
}
void MainWindow::InitializeSession(cpc::Language language, std::wstring const& resumeToken,
bool languageExplicit)
{
// C++/WinRT completes XAML connection after the authored constructor
// returns. Named controls are therefore first accessed here.
ConfigureWindow();
uiReady_ = true;
WindowRoot().ActualThemeChanged([weak = get_weak()](FrameworkElement const&, IInspectable const&)
{
if (auto self = weak.get())
{
HIGHCONTRASTW contrast{sizeof(contrast)};
const bool highContrast = SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0) &&
(contrast.dwFlags & HCF_HIGHCONTRASTON) != 0;
gRuntimeThemeKey = highContrast ? L"HighContrast" :
self->themeMode_ == cpc::ThemeMode::Dark ? L"Dark" :
self->themeMode_ == cpc::ThemeMode::Light ? L"Light" :
self->WindowRoot().ActualTheme() == ElementTheme::Dark ? L"Dark" : L"Light";
self->ApplyTitleBarTheme();
self->RefreshThemedVisuals();
}
});
try
{
accessibilitySettings_ = winrt::Windows::UI::ViewManagement::AccessibilitySettings();
accessibilitySettings_.HighContrastChanged([weak = get_weak()](auto const&, auto const&)
{
if (auto self = weak.get())
{
self->DispatcherQueue().TryEnqueue([weak]()
{
if (auto target = weak.get()) target->ApplyTheme();
});
}
});
uiSettings_ = winrt::Windows::UI::ViewManagement::UISettings();
uiSettings_.AnimationsEnabledChanged([weak = get_weak()](auto const&, auto const&)
{
if (auto self = weak.get()) self->DispatcherQueue().TryEnqueue([weak]()
{
if (auto target = weak.get()) target->SetBusy(target->busy_, L"", target->statusPercent_);
});
});
}
catch (...) {}
language_ = language;
LoadSettings(languageExplicit);
ApplyTheme();
Closed({this, &MainWindow::Window_Closed});
certificateFilterTimer_ = DispatcherTimer();
certificateFilterTimer_.Interval(std::chrono::milliseconds(250));
certificateFilterTimer_.Tick([weak = get_weak()](IInspectable const&, IInspectable const&)
{
if (auto self = weak.get())
{
self->certificateFilterTimer_.Stop();
self->PopulateCertificates();
}
});
backupValidationTimer_ = DispatcherTimer();
backupValidationTimer_.Interval(std::chrono::milliseconds(450));
backupValidationTimer_.Tick([weak = get_weak()](IInspectable const&, IInspectable const&)
{
if (auto self = weak.get())
{
self->backupValidationTimer_.Stop();
self->ProbeBackupPathAsync(self->backupValidationRevision_, self->backupValidationPath_);
}
});
BackupPath().TextChanged([weak = get_weak()](IInspectable const&, TextChangedEventArgs const&)
{
if (auto self = weak.get())
{
self->planRevisions_.BackupChanged();
self->InvalidatePlan();
self->ScheduleBackupValidation();
}
});
OfflinePath().TextChanged([weak = get_weak()](IInspectable const&, TextChangedEventArgs const&)
{
if (auto self = weak.get())
{
if (self->offlineScanRunning_ || !self->operationGate_.idle()) return;
const std::wstring entered = self->OfflinePath().Text().c_str();
if (self->offlineScanRevision_ && NormalizeUiPath(entered) != NormalizeUiPath(self->offlineInputPath_))
self->InvalidateOfflinePath();
self->offlineInputPath_ = entered;
}
});
ApplyAdaptiveLayout(WindowRoot().ActualWidth());
if (currentPage_ == L"certificates") Navigation().SelectedItem(NavCertificates());
else if (currentPage_ == L"offline") Navigation().SelectedItem(NavOffline());
else if (currentPage_ == L"reports") Navigation().SelectedItem(NavReports());
else if (currentPage_ == L"settings") Navigation().SelectedItem(NavSettings());
else if (currentPage_ == L"about") Navigation().SelectedItem(NavAbout());
else { currentPage_ = L"overview"; Navigation().SelectedItem(NavOverview()); }
NavigateTo(currentPage_);
resumeToken_ = resumeToken;
languageSync_ = true;
LanguageCombo().SelectedIndex(language_ == cpc::Language::Russian ? 0 : 1);
SettingsLanguageCombo().SelectedIndex(language_ == cpc::Language::Russian ? 0 : 1);
settingsSync_ = true;
ThemeCombo().SelectedIndex(std::min(static_cast<int>(themeMode_), 1));
RememberWindowToggle().IsOn(rememberWindow_);
ReduceMotionToggle().IsOn(reduceMotion_);
settingsSync_ = false;
languageSync_ = false;
ApplyLanguage();
ApplyTheme();
SaveSettings();
ExecutablePathText().Text(L"");
ExecutablePathText().Visibility(Visibility::Collapsed);
PWSTR documents = nullptr;
if (BackupPath().Text().empty() && SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &documents)))
{
BackupPath().Text(std::wstring(documents) + L"\\CryptoPro Backup");
CoTaskMemFree(documents);
}
if (!resumeToken_.empty())
{
// Defensive fallback for embedders: resume is always an exact
// residual pass and never enters the normal uninstaller dialog.
cpc::RunResumeCommand(resumeToken_, true);
Close();
return;
}
StartLiveScan();
}
HWND MainWindow::GetWindowHandle()
{
HWND hwnd = nullptr;
Microsoft::UI::Xaml::Window window = *this;
check_hresult(window.as<IWindowNative>()->get_WindowHandle(&hwnd));
return hwnd;
}
void MainWindow::ConfigureWindow()
{
Title(std::wstring(L"CryptoPro Cleanup Utility ") + cpc::kVersion);
const HWND hwnd = GetWindowHandle();
const UINT dpi = GetDpiForWindow(hwnd);
const int width = MulDiv(1440, static_cast<int>(dpi), 96);
const int height = MulDiv(920, static_cast<int>(dpi), 96);
HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY);
MONITORINFO monitorInfo{sizeof(monitorInfo)};
if (monitor && GetMonitorInfoW(monitor, &monitorInfo))
{
const int availableWidth = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
const int availableHeight = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
const int boundedWidth = std::min(width, availableWidth);
const int boundedHeight = std::min(height, availableHeight);
const int left = monitorInfo.rcWork.left + (availableWidth - boundedWidth) / 2;
const int top = monitorInfo.rcWork.top + (availableHeight - boundedHeight) / 2;
SetWindowPos(hwnd, nullptr, left, top, boundedWidth, boundedHeight, SWP_NOZORDER | SWP_NOACTIVATE);
}
const HICON icon = static_cast<HICON>(LoadImageW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(kIconResource),
IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));
if (icon)
{
SendMessageW(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(icon));
SendMessageW(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(icon));
}
}
void MainWindow::LoadSettings(bool languageExplicit)
{
DWORD value = 0;
if (ReadSettingDword(L"RememberWindow", &value)) rememberWindow_ = value != 0;
if (ReadSettingDword(L"ReduceMotion", &value)) reduceMotion_ = value != 0;
if (ReadSettingDword(L"Theme", &value)) themeMode_ = cpc::NormalizeThemeMode(value);
if (!languageExplicit && ReadSettingDword(L"Language", &value))
language_ = value == 1 ? cpc::Language::English : cpc::Language::Russian;
if (rememberWindow_)
{
const std::wstring page = ReadSettingString(L"LastPage");
if (page == L"overview" || page == L"certificates" || page == L"offline" ||
page == L"reports" || page == L"settings" || page == L"about") currentPage_ = page;
DWORD left = 0, top = 0, right = 0, bottom = 0;
if (ReadSettingDword(L"WindowLeft", &left) && ReadSettingDword(L"WindowTop", &top) &&
ReadSettingDword(L"WindowRight", &right) && ReadSettingDword(L"WindowBottom", &bottom))
{
RECT desired{static_cast<LONG>(left), static_cast<LONG>(top),
static_cast<LONG>(right), static_cast<LONG>(bottom)};
HMONITOR monitor = MonitorFromRect(&desired, MONITOR_DEFAULTTONULL);
MONITORINFO monitorInfo{sizeof(monitorInfo)};
if (desired.right - desired.left >= 700 && desired.bottom - desired.top >= 500 &&
monitor && GetMonitorInfoW(monitor, &monitorInfo))
{
const LONG width = std::min<LONG>(desired.right - desired.left,
monitorInfo.rcWork.right - monitorInfo.rcWork.left);
const LONG height = std::min<LONG>(desired.bottom - desired.top,
monitorInfo.rcWork.bottom - monitorInfo.rcWork.top);
const LONG boundedLeft = std::clamp<LONG>(desired.left, monitorInfo.rcWork.left,
monitorInfo.rcWork.right - width);
const LONG boundedTop = std::clamp<LONG>(desired.top, monitorInfo.rcWork.top,
monitorInfo.rcWork.bottom - height);
SetWindowPos(GetWindowHandle(), nullptr, boundedLeft, boundedTop, width, height,
SWP_NOZORDER | SWP_NOACTIVATE);
}
}
else
{
DWORD width = 0, height = 0;
if (ReadSettingDword(L"WindowWidth", &width) && ReadSettingDword(L"WindowHeight", &height) &&
width >= 900 && height >= 650 && width <= 4096 && height <= 2160)
{
const UINT dpi = GetDpiForWindow(GetWindowHandle());
SetWindowPos(GetWindowHandle(), nullptr, 0, 0,
MulDiv(static_cast<int>(width), static_cast<int>(dpi), 96),
MulDiv(static_cast<int>(height), static_cast<int>(dpi), 96),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
if (ReadSettingDword(L"WindowMaximized", &value) && value) ShowWindow(GetWindowHandle(), SW_MAXIMIZE);
}
}
void MainWindow::SaveSettings()
{
HKEY key = nullptr;
if (RegCreateKeyExW(HKEY_CURRENT_USER, kSettingsKey, 0, nullptr, 0, KEY_SET_VALUE,
nullptr, &key, nullptr) != ERROR_SUCCESS) return;
WriteSettingDword(key, L"Language", language_ == cpc::Language::English ? 1 : 0);
WriteSettingDword(key, L"Theme", static_cast<DWORD>(themeMode_));
WriteSettingDword(key, L"RememberWindow", rememberWindow_ ? 1 : 0);
WriteSettingDword(key, L"ReduceMotion", reduceMotion_ ? 1 : 0);
if (rememberWindow_)
{
WINDOWPLACEMENT placement{sizeof(placement)};
if (GetWindowPlacement(GetWindowHandle(), &placement))
{
const RECT rectangle = placement.rcNormalPosition;
const UINT dpi = GetDpiForWindow(GetWindowHandle());
WriteSettingDword(key, L"WindowWidth", static_cast<DWORD>(MulDiv(rectangle.right - rectangle.left, 96, dpi)));
WriteSettingDword(key, L"WindowHeight", static_cast<DWORD>(MulDiv(rectangle.bottom - rectangle.top, 96, dpi)));
WriteSettingDword(key, L"WindowLeft", static_cast<DWORD>(rectangle.left));
WriteSettingDword(key, L"WindowTop", static_cast<DWORD>(rectangle.top));
WriteSettingDword(key, L"WindowRight", static_cast<DWORD>(rectangle.right));
WriteSettingDword(key, L"WindowBottom", static_cast<DWORD>(rectangle.bottom));
WriteSettingDword(key, L"WindowMaximized", IsZoomed(GetWindowHandle()) ? 1 : 0);
}
WriteSettingString(key, L"LastPage", currentPage_);
}
RegCloseKey(key);
}
void MainWindow::ApplyTheme()
{
switch (themeMode_)
{
case cpc::ThemeMode::System: WindowRoot().RequestedTheme(ElementTheme::Default); break;
case cpc::ThemeMode::Light: WindowRoot().RequestedTheme(ElementTheme::Light); break;
default: WindowRoot().RequestedTheme(ElementTheme::Dark); break;
}
HIGHCONTRASTW contrast{sizeof(contrast)};
const bool highContrast = SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0) &&
(contrast.dwFlags & HCF_HIGHCONTRASTON) != 0;
gRuntimeThemeKey = highContrast ? L"HighContrast" :
themeMode_ == cpc::ThemeMode::Dark ? L"Dark" :
themeMode_ == cpc::ThemeMode::Light ? L"Light" :
WindowRoot().ActualTheme() == ElementTheme::Dark ? L"Dark" : L"Light";
HighContrastStatus().Text(highContrast
? T(L"Высокий контраст Windows включён.", L"Windows high contrast is enabled.")
: T(L"Высокий контраст Windows выключен.", L"Windows high contrast is disabled."));
ApplyTitleBarTheme();
RefreshThemedVisuals();
}
void MainWindow::ApplyTitleBarTheme()
{
const BOOL dark = WindowRoot().ActualTheme() == ElementTheme::Dark ? TRUE : FALSE;
if (HMODULE dwm = LoadLibraryW(L"dwmapi.dll"))
{
using DwmSetWindowAttributeFn = HRESULT (WINAPI*)(HWND, DWORD, LPCVOID, DWORD);
if (auto setAttribute = reinterpret_cast<DwmSetWindowAttributeFn>(GetProcAddress(dwm, "DwmSetWindowAttribute")))
{
if (FAILED(setAttribute(GetWindowHandle(), 20, &dark, sizeof(dark))))
setAttribute(GetWindowHandle(), 19, &dark, sizeof(dark));
}
FreeLibrary(dwm);
}
}
void MainWindow::RefreshThemedVisuals()
{
if (!uiReady_) return;
// Static controls use ThemeResource. Runtime rows keep their model,
// handlers, focus, and selection; only brushes are refreshed here.
for (auto const& child : ProductsPanel().Children())
if (auto border = child.try_as<Border>()) border.BorderBrush(ThemeBrush(L"DividerBrush"));
for (auto const& child : OfflineProductsPanel().Children())
if (auto border = child.try_as<Border>()) border.BorderBrush(ThemeBrush(L"DividerBrush"));
for (auto const& item : CertificatesPanel().Items())
if (auto button = item.try_as<Button>()) button.BorderBrush(ThemeBrush(L"DividerBrush"));
RefreshBadgeThemes(WindowRoot());
RefreshCertificateSelectionVisuals();
RefreshCompactNavigationVisuals();
RenderStatus();
}
void MainWindow::RefreshCompactNavigationVisuals()
{
const auto clear = ThemeBrush(L"NavigationBackgroundBrush");
const auto selected = ThemeBrush(L"SurfaceSelectedBrush");
const auto foreground = ThemeBrush(L"PrimaryTextBrush");
auto apply = [&](Button const& button, bool active)
{
button.Background(active ? selected : clear);
button.Foreground(foreground);
button.BorderBrush(active ? selected : clear);
};
apply(CompactOverview(), currentPage_ == L"overview");
apply(CompactCertificates(), currentPage_ == L"certificates");
apply(CompactOffline(), currentPage_ == L"offline");
apply(CompactReports(), currentPage_ == L"reports");
apply(CompactSettings(), currentPage_ == L"settings");
apply(CompactAbout(), currentPage_ == L"about");
}
void MainWindow::Window_Closed(IInspectable const&, WindowEventArgs const& args)
{
if (!operationGate_.idle())
{
args.Handled(true);
ShowMessage(T(L"Операция ещё выполняется", L"An operation is still running"),
T(L"Дождитесь завершения текущего этапа. Закрытие сейчас заблокировано.",
L"Wait for the current stage to finish. Closing is blocked for now."));
return;
}
closing_ = true;
dialogQueue_.clear();
SaveSettings();
}
void MainWindow::WindowRoot_SizeChanged(IInspectable const&, SizeChangedEventArgs const& args)
{
if (!uiReady_) return;
if (!enforcingMinimumSize_ && (args.NewSize().Width < 900 || args.NewSize().Height < 650))
{
enforcingMinimumSize_ = true;
RECT rectangle{};
GetWindowRect(GetWindowHandle(), &rectangle);
const UINT dpi = GetDpiForWindow(GetWindowHandle());
SetWindowPos(GetWindowHandle(), nullptr, 0, 0,
std::max<LONG>(rectangle.right - rectangle.left,
static_cast<LONG>(MulDiv(900, static_cast<int>(dpi), 96))),
std::max<LONG>(rectangle.bottom - rectangle.top,
static_cast<LONG>(MulDiv(650, static_cast<int>(dpi), 96))),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
enforcingMinimumSize_ = false;
}
ApplyAdaptiveLayout(args.NewSize().Width);
}
void MainWindow::ApplyAdaptiveLayout(double width)
{
if (width <= 0) width = 1440;
const bool compact = width < 1180;
if (compact != compactNavigation_)
{
compactNavigation_ = compact;
Navigation().PaneDisplayMode(compact ? NavigationViewPaneDisplayMode::LeftMinimal
: NavigationViewPaneDisplayMode::Left);
Navigation().IsPaneOpen(!compact);
Navigation().IsPaneToggleButtonVisible(false);
Navigation().Margin(compact ? Thickness{48, 0, 0, 0} : Thickness{0, 0, 0, 0});
CompactRail().Visibility(compact ? Visibility::Visible : Visibility::Collapsed);
}
const double contentWidth = width - (compact ? 48.0 : 248.0);
auto setColumn = [](Grid const& grid, uint32_t index, double value, GridUnitType unit)
{
grid.ColumnDefinitions().GetAt(index).Width(GridLength{value, unit});
};
const bool stackHeader = contentWidth < 900;
Grid::SetColumn(HeaderActions(), stackHeader ? 0 : 1);
Grid::SetRow(HeaderActions(), stackHeader ? 1 : 0);
Grid::SetColumnSpan(HeaderActions(), stackHeader ? 2 : 1);
HeaderActions().HorizontalAlignment(stackHeader ? HorizontalAlignment::Left : HorizontalAlignment::Right);
const bool stackBackupPath = contentWidth < 760;
setColumn(BackupPathGrid(), 0, 1.0, GridUnitType::Star);
setColumn(BackupPathGrid(), 1, stackBackupPath ? 0.0 : 1.0,
stackBackupPath ? GridUnitType::Pixel : GridUnitType::Auto);
Grid::SetColumn(ChooseBackupButton(), stackBackupPath ? 0 : 1);
Grid::SetRow(ChooseBackupButton(), stackBackupPath ? 1 : 0);
ChooseBackupButton().HorizontalAlignment(stackBackupPath ? HorizontalAlignment::Left : HorizontalAlignment::Stretch);
const bool twoColumnStats = contentWidth < 930;
for (uint32_t index = 0; index < 4; ++index)
setColumn(OverviewStatsGrid(), index, index < (twoColumnStats ? 2u : 4u) ? 1.0 : 0.0,
index < (twoColumnStats ? 2u : 4u) ? GridUnitType::Star : GridUnitType::Pixel);
Grid::SetColumn(ProductsStatCard(), 0); Grid::SetRow(ProductsStatCard(), 0);
Grid::SetColumn(LicensesStatCard(), 1); Grid::SetRow(LicensesStatCard(), 0);
Grid::SetColumn(CertificatesStatCard(), twoColumnStats ? 0 : 2); Grid::SetRow(CertificatesStatCard(), twoColumnStats ? 1 : 0);
Grid::SetColumn(RiskStatCard(), twoColumnStats ? 1 : 3); Grid::SetRow(RiskStatCard(), twoColumnStats ? 1 : 0);
const bool stackOverview = contentWidth < 980;
setColumn(OverviewContentGrid(), 0, stackOverview ? 1.0 : 2.2, GridUnitType::Star);
setColumn(OverviewContentGrid(), 1, stackOverview ? 0.0 : 1.0,
stackOverview ? GridUnitType::Pixel : GridUnitType::Star);
Grid::SetColumn(OverviewLeftColumn(), 0); Grid::SetRow(OverviewLeftColumn(), 0);
Grid::SetColumn(PlanCard(), stackOverview ? 0 : 1); Grid::SetRow(PlanCard(), stackOverview ? 1 : 0);
PlanCard().Margin(stackOverview ? Thickness{0, 0, 0, 0} : Thickness{0, 0, 0, 0});
const bool stackBottom = contentWidth < 760;
setColumn(OverviewBottomGrid(), 0, 1.0, GridUnitType::Star);
setColumn(OverviewBottomGrid(), 1, stackBottom ? 0.0 : 1.25,
stackBottom ? GridUnitType::Pixel : GridUnitType::Star);
Grid::SetColumn(ProfilesCard(), 0); Grid::SetRow(ProfilesCard(), 0);
Grid::SetColumn(BackupCard(), stackBottom ? 0 : 1); Grid::SetRow(BackupCard(), stackBottom ? 1 : 0);
const bool stackCertificates = contentWidth < 1010;
setColumn(CertificatesContentGrid(), 0, stackCertificates ? 1.0 : 2.3, GridUnitType::Star);
setColumn(CertificatesContentGrid(), 1, stackCertificates ? 0.0 : 1.0,
stackCertificates ? GridUnitType::Pixel : GridUnitType::Star);
Grid::SetColumn(CertificatesListCard(), 0); Grid::SetRow(CertificatesListCard(), 0);
Grid::SetColumn(CertificateDetailsCard(), stackCertificates ? 0 : 1);
Grid::SetRow(CertificateDetailsCard(), stackCertificates ? 1 : 0);
const bool stackCertificateFilters = contentWidth < 880;
setColumn(CertificateFilterGrid(), 0, 1.0, GridUnitType::Star);
setColumn(CertificateFilterGrid(), 1, stackCertificateFilters ? 1.0 : 150.0,
stackCertificateFilters ? GridUnitType::Star : GridUnitType::Pixel);
setColumn(CertificateFilterGrid(), 2, stackCertificateFilters ? 0.0 : 150.0,
GridUnitType::Pixel);
Grid::SetColumn(CertificateProfileFilter(), stackCertificateFilters ? 0 : 1);
Grid::SetRow(CertificateProfileFilter(), stackCertificateFilters ? 1 : 0);
Grid::SetColumn(CertificateKeyFilter(), stackCertificateFilters ? 1 : 2);
Grid::SetRow(CertificateKeyFilter(), stackCertificateFilters ? 1 : 0);
Grid::SetRow(CertificateBulkActions(), stackCertificateFilters ? 2 : 1);
for (uint32_t index = 0; index < 4; ++index)
setColumn(OfflineStatsGrid(), index, index < (twoColumnStats ? 2u : 4u) ? 1.0 : 0.0,
index < (twoColumnStats ? 2u : 4u) ? GridUnitType::Star : GridUnitType::Pixel);
Grid::SetColumn(OfflineProductsStatCard(), 0); Grid::SetRow(OfflineProductsStatCard(), 0);
Grid::SetColumn(OfflineLicensesStatCard(), 1); Grid::SetRow(OfflineLicensesStatCard(), 0);
Grid::SetColumn(OfflineCertsStatCard(), twoColumnStats ? 0 : 2); Grid::SetRow(OfflineCertsStatCard(), twoColumnStats ? 1 : 0);
Grid::SetColumn(OfflineTargetsStatCard(), twoColumnStats ? 1 : 3); Grid::SetRow(OfflineTargetsStatCard(), twoColumnStats ? 1 : 0);
const bool stackOffline = contentWidth < 980;
setColumn(OfflineContentGrid(), 0, stackOffline ? 1.0 : 2.2, GridUnitType::Star);
setColumn(OfflineContentGrid(), 1, stackOffline ? 0.0 : 1.0,
stackOffline ? GridUnitType::Pixel : GridUnitType::Star);
Grid::SetColumn(OfflineResultsCard(), 0); Grid::SetRow(OfflineResultsCard(), 0);
Grid::SetColumn(OfflineRescueCard(), stackOffline ? 0 : 1); Grid::SetRow(OfflineRescueCard(), stackOffline ? 1 : 0);
const bool stackSettings = contentWidth < 760;
for (auto const& row : {SettingsLanguageRow(), SettingsThemeRow()})
{
setColumn(row, 0, 1.0, GridUnitType::Star);
setColumn(row, 1, stackSettings ? 0.0 : 220.0,
stackSettings ? GridUnitType::Pixel : GridUnitType::Pixel);
}
Grid::SetColumn(SettingsLanguageCombo(), stackSettings ? 0 : 1);
Grid::SetRow(SettingsLanguageCombo(), stackSettings ? 1 : 0);
Grid::SetColumn(ThemeCombo(), stackSettings ? 0 : 1);
Grid::SetRow(ThemeCombo(), stackSettings ? 1 : 0);
SettingsLanguageCombo().HorizontalAlignment(stackSettings ? HorizontalAlignment::Stretch : HorizontalAlignment::Right);
ThemeCombo().HorizontalAlignment(stackSettings ? HorizontalAlignment::Stretch : HorizontalAlignment::Right);
}
std::wstring MainWindow::T(wchar_t const* russian, wchar_t const* english) const
{
return language_ == cpc::Language::Russian ? russian : english;
}
void MainWindow::Navigation_ItemInvoked(NavigationView const&, NavigationViewItemInvokedEventArgs const& args)
{
const auto item = args.InvokedItemContainer();
if (!item) return;
const auto tag = item.Tag();
if (!tag) return;
NavigateTo(unbox_value<hstring>(tag).c_str());
}
void MainWindow::CompactNavigation_Click(IInspectable const& sender, RoutedEventArgs const&)
{
const auto button = sender.try_as<Button>();
if (!button || !button.Tag()) return;
const std::wstring page = unbox_value<hstring>(button.Tag()).c_str();
if (page == L"overview") Navigation().SelectedItem(NavOverview());
else if (page == L"certificates") Navigation().SelectedItem(NavCertificates());
else if (page == L"offline") Navigation().SelectedItem(NavOffline());
else if (page == L"reports") Navigation().SelectedItem(NavReports());
else if (page == L"settings") Navigation().SelectedItem(NavSettings());
else if (page == L"about") Navigation().SelectedItem(NavAbout());
else return;
NavigateTo(page);
}
void MainWindow::NavigateTo(std::wstring const& page)
{
currentPage_ = page;
const auto visible = Visibility::Visible;
const auto collapsed = Visibility::Collapsed;
OverviewPage().Visibility(page == L"overview" ? visible : collapsed);
CertificatesPage().Visibility(page == L"certificates" ? visible : collapsed);
OfflinePage().Visibility(page == L"offline" ? visible : collapsed);
ReportsPage().Visibility(page == L"reports" ? visible : collapsed);
SettingsPage().Visibility(page == L"settings" ? visible : collapsed);
AboutPage().Visibility(page == L"about" ? visible : collapsed);
RescanButton().Visibility(page == L"overview" || page == L"certificates" ? visible : collapsed);
RefreshCompactNavigationVisuals();
UpdatePageHeader();
if (page == L"reports") UpdateReportsPage();
}
void MainWindow::UpdatePageHeader()
{
if (currentPage_ == L"overview")
{
PageEyebrow().Text(T(L"РАБОТАЮЩАЯ СИСТЕМА · БЕЗОПАСНОЕ СКАНИРОВАНИЕ", L"LIVE SYSTEM · SAFE SCAN"));
PageTitle().Text(T(L"Обзор системы", L"System overview"));
PageSubtitle().Text(T(L"Проверь найденные продукты, резервную копию и план операции.",
L"Review detected products, the backup folder, and the operation plan."));
}
else if (currentPage_ == L"certificates")
{
PageEyebrow().Text(T(L"ОТКРЫТЫЕ СЕРТИФИКАТЫ · ТОЛЬКО ПУБЛИЧНАЯ ЧАСТЬ", L"PUBLIC CERTIFICATES · PUBLIC PART ONLY"));
PageTitle().Text(T(L"Открытые сертификаты", L"Public certificates"));
PageSubtitle().Text(T(L"Выберите публичную часть для экспорта в .cer и общий .p7b.",
L"Select public certificates to export as .cer files and one .p7b bundle."));
}
else if (currentPage_ == L"offline")
{
PageEyebrow().Text(T(L"ОТКЛЮЧЁННАЯ WINDOWS · СНАЧАЛА ТОЛЬКО ЧТЕНИЕ", L"OFFLINE WINDOWS · READ-ONLY FIRST"));
PageTitle().Text(T(L"Офлайн-Windows", L"Offline Windows"));
PageSubtitle().Text(T(L"Можно выбрать корень подключённого диска или находящуюся на нём папку Windows.",
L"Select either the attached drive root or its Windows directory."));
}
else if (currentPage_ == L"reports")
{
PageEyebrow().Text(T(L"ОТЧЁТЫ · БЕЗ ПЕРСОНАЛЬНЫХ ДАННЫХ", L"REPORTS · NO PERSONAL DATA"));
PageTitle().Text(T(L"Журнал и отчёты", L"Log and reports"));
PageSubtitle().Text(T(L"Здесь отображается обезличенный ход операций и созданные файлы.",
L"This page shows the redacted operation log and generated files."));
}
else if (currentPage_ == L"settings")
{
PageEyebrow().Text(T(L"ПРИЛОЖЕНИЕ · ЛОКАЛЬНЫЕ НАСТРОЙКИ", L"APPLICATION · LOCAL SETTINGS"));
PageTitle().Text(T(L"Настройки", L"Settings"));
PageSubtitle().Text(T(L"Параметры интерфейса не содержат лицензий, сертификатов и целей очистки.",
L"Interface settings never contain licenses, certificates, or cleanup targets."));
}
else
{
PageEyebrow().Text(T(L"О ПРОЕКТЕ · ОТКРЫТЫЙ ИСХОДНЫЙ КОД", L"ABOUT · OPEN SOURCE"));
PageTitle().Text(T(L"О программе", L"About"));
PageSubtitle().Text(T(L"Версия, автор, лицензия и важная информация о проекте.",
L"Version, author, license, and important project information."));
}
}
void MainWindow::ApplyLanguage()
{
// Detailed progress is transient. Re-render it from the semantic
// operation source so a language switch never leaves stale text.
statusDetail_.clear();
Title(T(L"КриптоПро Очистка ", L"CryptoPro Cleanup Utility ") + std::wstring(cpc::kVersion));
BrandTitle().Text(T(L"КриптоПро\nОчистка", L"CryptoPro\nCleanup"));
NavOverview().Content(box_value(T(L"Обзор", L"Overview")));
NavCertificates().Content(box_value(T(L"Открытые сертификаты", L"Public certificates")));
NavOffline().Content(box_value(T(L"Офлайн-Windows", L"Offline Windows")));
NavReports().Content(box_value(T(L"Журнал и отчёты", L"Log and reports")));
NavSettings().Content(box_value(T(L"Настройки", L"Settings")));
NavAbout().Content(box_value(T(L"О программе", L"About")));
SafetyCaption().Text(T(L"СОСТОЯНИЕ ЗАЩИТЫ", L"PROTECTION STATUS"));
SafetyText().Text(T(L"Контейнеры ключей и хранилища сертификатов исключены из очистки",
L"Key containers and certificate stores are excluded from cleanup"));
SafetyActive().Text(T(L"Политика безопасности активна", L"Safety policy is active"));
WebsiteLink().Content(box_value(T(L"Сайт", L"Website")));
SupportLink().Content(box_value(T(L"Поддержать", L"Support")));
RescanButtonText().Text(T(L"Повторить сканирование", L"Scan again"));
ProductsStatCaption().Text(T(L"ПРОДУКТЫ", L"PRODUCTS"));
LicensesStatCaption().Text(T(L"ЛИЦЕНЗИИ", L"LICENSES"));
CertificatesStatCaption().Text(T(L"СЕРТИФИКАТЫ", L"CERTIFICATES"));
RiskStatCaption().Text(T(L"ВЫСОКИЙ РИСК", L"HIGH RISK"));
ProductsStatHint().Text(T(L"подтверждённый издатель", L"verified publisher"));
LicensesStatHint().Text(T(L"полные номера найдены", L"full serials found"));
CertificatesStatHint().Text(T(L"только открытая часть", L"public part only"));
RiskStatHint().Text(T(L"критичные продукты", L"critical products"));
ProductsTitle().Text(T(L"Обнаруженные продукты", L"Detected products"));
ProductsSubtitle().Text(T(L"Удаляются только записи подтверждённого издателя", L"Only verified-publisher entries can be removed"));
ProductColumn().Text(T(L"ПРОДУКТ", L"PRODUCT"));
VersionColumn().Text(T(L"ВЕРСИЯ", L"VERSION"));
ArchitectureColumn().Text(T(L"АРХИТЕКТУРА", L"ARCHITECTURE"));
RiskColumn().Text(T(L"РИСК", L"RISK"));
ProfilesTitle().Text(T(L"Профили для очистки", L"Profiles to clean"));
ProfilesSubtitle().Text(T(L"Настройки выбранных локальных профилей", L"Settings of selected local profiles"));
BackupTitle().Text(T(L"Резервная копия", L"Backup"));
BackupSubtitle().Text(T(L"Создаётся до любых изменений", L"Created before any changes"));
ChooseBackupText().Text(T(L"Изменить", L"Change"));
BackupInfo().Text(T(L"Будут созданы licenses.txt, папка certificates, summary.txt, report.json и обезличенный cleanup.log.",
L"Creates licenses.txt, a certificates folder, summary.txt, report.json, and a redacted cleanup.log."));
ValidateBackupPathForUi();
ShowLicensesText().Text(T(L"Показать и копировать лицензии", L"Show and copy licenses"));
PlanCaption().Text(T(L"ПЛАН ОПЕРАЦИИ", L"OPERATION PLAN"));
PlanState().Text(planRevisions_.IsPlanCurrent()
? T(L"План проверен", L"Plan reviewed")
: (planRevisions_.planReady ? T(L"Требуется повторная проверка", L"Review required again")
: T(L"Готово к проверке", L"Ready to review")));
PlanTargetLabel().Text(T(L"подтверждённых\nцелей очистки", L"verified cleanup\ntargets"));
PlanStep1().Text(T(L"Создать резервную копию", L"Create a backup"));
PlanStep1Hint().Text(T(L"лицензии, сертификаты и отчёты", L"licenses, certificates, and reports"));
PlanStep2().Text(T(L"Запустить штатные деинсталляторы", L"Run registered uninstallers"));
PlanStep2Hint().Text(T(L"сначала MSI/EXE, без принудительной очистки", L"MSI/EXE first, without forced cleanup"));
PlanStep3().Text(T(L"Удалить подтверждённые остатки", L"Remove verified residuals"));
PlanStep3Hint().Text(T(L"только цели проверенного плана", L"verified plan targets only"));
PlanStep4().Text(T(L"Повторно проверить систему", L"Verify the system again"));
PlanStep4Hint().Text(T(L"отчёт с точными остатками", L"report with exact residuals"));
ProtectedTitle().Text(T(L"Защищённые данные не затрагиваются", L"Protected data remains untouched"));
ProtectedHint().Text(T(L"Закрытые ключи · токены · хранилища Windows", L"Private keys · tokens · Windows stores"));
CheckPlanText().Text(T(L"Проверить план", L"Review plan"));
CertSafetyTitle().Text(T(L"Закрытые ключи не экспортируются", L"Private keys are never exported"));
CertSafetyHint().Text(T(L"Программа показывает только открытую часть сертификатов и наличие ссылки на ключ.",
L"The utility shows only the public certificate and whether a private-key reference exists."));
CertificateSearch().PlaceholderText(T(L"Поиск по владельцу, издателю, профилю или отпечатку", L"Search owner, issuer, profile, or thumbprint"));
CertSubjectColumn().Text(T(L"КОМУ ВЫДАН", L"ISSUED TO"));
CertProfileColumn().Text(T(L"ПРОФИЛЬ", L"PROFILE"));
CertValidColumn().Text(T(L"ДЕЙСТВУЕТ ПО", L"VALID TO"));
CertKeyColumn().Text(T(L"КЛЮЧ", L"KEY"));
ExportCertificatesText().Text(T(L"Экспортировать выбранные", L"Export selected"));
SelectedCertCaption().Text(T(L"ВЫБРАННЫЙ СЕРТИФИКАТ", L"SELECTED CERTIFICATE"));
CopyThumbprintText().Text(T(L"Копировать отпечаток", L"Copy thumbprint"));
OfflinePathCaption().Text(T(L"ДИСК ИЛИ ПАПКА WINDOWS", L"DRIVE OR WINDOWS DIRECTORY"));
OfflinePath().PlaceholderText(T(L"Например, E:\\ или E:\\Windows", L"For example, E:\\ or E:\\Windows"));
ChooseOfflineText().Text(T(L"Выбрать", L"Browse"));
ScanOfflineText().Text(T(L"Безопасно сканировать", L"Safe scan"));
OfflineProductsCaption().Text(T(L"ПРОДУКТЫ", L"PRODUCTS"));
OfflineLicensesCaption().Text(T(L"ЛИЦЕНЗИИ", L"LICENSES"));
OfflineCertsCaption().Text(T(L"СЕРТИФИКАТЫ", L"CERTIFICATES"));
OfflineTargetsCaption().Text(T(L"ЦЕЛИ ОЧИСТКИ", L"CLEANUP TARGETS"));
OfflineProductsTitle().Text(T(L"Продукты в отключённой Windows", L"Products in offline Windows"));
OfflineRescueTitle().Text(T(L"Безопасное спасение данных", L"Safe data rescue"));
OfflineRescueHint().Text(T(L"Сначала сохраняются лицензии и выбранные открытые сертификаты. Отключённая Windows при этом не изменяется.",
L"Licenses and selected public certificates are saved first. The offline Windows installation is not modified."));
ShowOfflineLicensesText().Text(T(L"Показать и копировать лицензии", L"Show and copy licenses"));
SaveOfflineText().Text(T(L"Сохранить найденные данные", L"Save rescued data"));
CleanOfflineText().Text(T(L"Расширенная офлайн-очистка", L"Advanced offline cleanup"));
ReportPrivacyTitle().Text(T(L"Обезличенный журнал", L"Redacted log"));
ReportPrivacyHint().Text(T(L"Полные лицензии и персональные имена сертификатов сюда не попадают. Они сохраняются только в отдельных конфиденциальных файлах.",
L"Full licenses and certificate personal names are not shown here. They are written only to separate confidential files."));
ToggleTechnicalLogText().Text(technicalLogExpanded_
? T(L"Скрыть технический журнал", L"Hide technical log")
: T(L"Показать технический журнал", L"Show technical log"));
CopyLogText().Text(T(L"Копировать журнал", L"Copy log"));
OpenReportFolderText().Text(T(L"Открыть папку отчёта", L"Open report folder"));
OpenJsonText().Text(T(L"Открыть JSON", L"Open JSON"));
OpenSummaryText().Text(T(L"Открыть сводку", L"Open summary"));
OpenCleanupLogText().Text(T(L"Открыть cleanup.log", L"Open cleanup.log"));
OpenOfflineSummaryText().Text(T(L"Открыть offline-summary.txt", L"Open offline-summary.txt"));
OpenOfflineReportText().Text(T(L"Открыть offline-report.json", L"Open offline-report.json"));
OpenOfflineDiagnosticsText().Text(T(L"Открыть offline-diagnostics.txt", L"Open offline-diagnostics.txt"));
OpenOfflineResultText().Text(T(L"Открыть offline-result.txt", L"Open offline-result.txt"));
OpenOfflineCleanupLogText().Text(T(L"Открыть offline-cleanup.log", L"Open offline-cleanup.log"));
OpenLicensesText().Text(T(L"Открыть licenses.txt", L"Open licenses.txt"));
OpenCertificatesTextText().Text(T(L"Открыть certificates.txt", L"Open certificates.txt"));
OpenCertificatesBundleText().Text(T(L"Открыть certificates.p7b", L"Open certificates.p7b"));
OpenRecoveryMapText().Text(T(L"Открыть recovery-map.txt", L"Open recovery-map.txt"));
ReportOperationsCaption().Text(T(L"ОПЕРАЦИИ", L"OPERATIONS"));
ReportFailuresCaption().Text(T(L"ОШИБКИ", L"FAILURES"));
ReportResidualsCaption().Text(T(L"ОСТАТКИ", L"RESIDUALS"));
InterfaceSettingsTitle().Text(T(L"Интерфейс", L"Interface"));
SettingsLanguageTitle().Text(T(L"Язык интерфейса", L"Interface language"));
SettingsLanguageHint().Text(T(L"Переключение не сбрасывает результаты сканирования и выбор.",
L"Changing language preserves scan results and selections."));
RememberWindowToggle().Header(box_value(T(L"Запоминать размер окна и последнюю страницу", L"Remember window size and last page")));
ReduceMotionToggle().Header(box_value(T(L"Уменьшить анимацию интерфейса", L"Reduce interface motion")));
ThemeTitle().Text(T(L"Тема", L"Theme"));
settingsSync_ = true;
ThemeCombo().Items().Clear();
for (auto const& label : {T(L"Тёмная", L"Dark"), T(L"Системная", L"System"), T(L"Светлая", L"Light")})
{
ComboBoxItem item;
item.Content(box_value(label));
ThemeCombo().Items().Append(item);
}
ThemeCombo().SelectedIndex(static_cast<int>(themeMode_));
settingsSync_ = false;
ThemeHint().Text(T(L"Тёмная, светлая или системная тема; высокий контраст определяется Windows.",
L"Dark, light, or system theme; high contrast is detected from Windows."));
ResetSettingsText().Text(T(L"Сбросить настройки интерфейса", L"Reset interface settings"));
SelectFilteredCertificatesText().Text(T(L"Выбрать отфильтрованные", L"Select filtered"));
DeselectAllCertificatesText().Text(T(L"Снять выбор с отфильтрованных", L"Deselect filtered"));
OfflineCertificatesTitle().Text(T(L"Открытые сертификаты для сохранения", L"Public certificates to save"));
OfflineDiagnosticsButtonText().Text(T(L"Открыть диагностику", L"Open diagnostics"));
AboutDescription().Text(T(L"Открытая portable-утилита для контролируемого удаления продуктов CryptoPro, спасения лицензий и экспорта открытой части сертификатов.",
L"Open portable utility for controlled CryptoPro removal, license rescue, and public-certificate export."));
AboutDisclaimer().Text(T(L"Это неофициальный проект. Он не связан с ООО «КРИПТО-ПРО» и не одобрен правообладателем продуктов CryptoPro.",
L"This is an unofficial project. It is not affiliated with or endorsed by Crypto-Pro LLC."));
FooterVersion().Text(T(L"КОД АЛЕКСАНДРОВА · ", L"CODE ALEXANDROV · ") + std::wstring(cpc::kVersion));
AboutVersion().Text(T(L"Версия ", L"Version ") + std::wstring(cpc::kVersion));
AboutPlatformInfo().Text(T(
L"Редакция: Modern x64 · C++17 / WinUI 3\nМинимальная ОС: Windows 10 версии 1809\nВ комплекте также доступна отдельная Legacy x86 для Windows 7 SP1–Windows 11.",
L"Edition: Modern x64 · C++17 / WinUI 3\nMinimum OS: Windows 10 version 1809\nA separate Legacy x86 edition for Windows 7 SP1–Windows 11 is also included."));
AboutAuthor().Text(T(L"Автор: Кирилл Александров · лицензия MIT", L"Author: Kirill Alexandrov · MIT License"));
ComputeHashText().Text(T(L"Вычислить SHA-256", L"Compute SHA-256"));
ShowLocationText().Text(T(L"Показать расположение", L"Show location"));
CopyExecutablePathText().Text(T(L"Копировать путь", L"Copy path"));
OpenExecutableFolderText().Text(T(L"Открыть папку программы", L"Open program folder"));
AboutSupportButton().Content(box_value(T(L"Поддержать проект", L"Support the project")));
UpdateAboutSecurityState();
using Microsoft::UI::Xaml::Automation::AutomationProperties;
AutomationProperties::SetName(CompactOverview(), T(L"Обзор", L"Overview"));
AutomationProperties::SetName(CompactCertificates(), T(L"Открытые сертификаты", L"Public certificates"));
AutomationProperties::SetName(CompactOffline(), T(L"Офлайн-Windows", L"Offline Windows"));
AutomationProperties::SetName(CompactReports(), T(L"Журнал и отчёты", L"Log and reports"));
AutomationProperties::SetName(CompactSettings(), T(L"Настройки", L"Settings"));
AutomationProperties::SetName(CompactAbout(), T(L"О программе", L"About"));
RenderStatus();
UpdatePageHeader();
PopulateProducts();
PopulateProfiles();
PopulateCertificateFilters();
PopulateCertificates();
PopulateOfflineScan();
UpdateSelectedCounts();
const bool recognizableScanSummary = logText_.find(L'\n') == std::wstring::npos &&
(logText_.rfind(L"Безопасное сканирование завершено:", 0) == 0 ||
logText_.rfind(L"Safe scan completed:", 0) == 0);
if (liveScanSummaryOnly_ || recognizableScanSummary)
{
logText_ = LiveScanSummaryText();
liveScanSummaryOnly_ = true;
}
UpdateReportsPage();
}
void MainWindow::LanguageCombo_SelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
{
if (languageSync_) return;
language_ = LanguageCombo().SelectedIndex() == 0 ? cpc::Language::Russian : cpc::Language::English;
languageSync_ = true;
SettingsLanguageCombo().SelectedIndex(LanguageCombo().SelectedIndex());
languageSync_ = false;
ApplyLanguage();
ApplyTheme();
SaveSettings();
}
void MainWindow::ThemeCombo_SelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
{
if (settingsSync_ || !uiReady_) return;
themeMode_ = cpc::NormalizeThemeMode(static_cast<DWORD>(ThemeCombo().SelectedIndex()));
ApplyTheme();
SaveSettings();
}
void MainWindow::SettingsToggle_Toggled(IInspectable const&, RoutedEventArgs const&)
{
if (settingsSync_ || !uiReady_) return;
rememberWindow_ = RememberWindowToggle().IsOn();
reduceMotion_ = ReduceMotionToggle().IsOn();
ApplyAdaptiveLayout(WindowRoot().ActualWidth());
SetBusy(busy_, L"", statusPercent_);
SaveSettings();
}
void MainWindow::ResetSettings_Click(IInspectable const&, RoutedEventArgs const&)
{
RegDeleteTreeW(HKEY_CURRENT_USER, kSettingsKey);
rememberWindow_ = true;
reduceMotion_ = false;
themeMode_ = cpc::ThemeMode::Dark;
settingsSync_ = true;
ThemeCombo().SelectedIndex(0);
RememberWindowToggle().IsOn(true);
ReduceMotionToggle().IsOn(false);
settingsSync_ = false;
ApplyTheme();
ApplyAdaptiveLayout(WindowRoot().ActualWidth());
FooterStatus().Text(T(L"Настройки интерфейса сброшены.", L"Interface settings were reset."));
}
void MainWindow::SettingsLanguageCombo_SelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
{
if (languageSync_) return;
language_ = SettingsLanguageCombo().SelectedIndex() == 0 ? cpc::Language::Russian : cpc::Language::English;
languageSync_ = true;
LanguageCombo().SelectedIndex(SettingsLanguageCombo().SelectedIndex());
languageSync_ = false;
ApplyLanguage();
ApplyTheme();
SaveSettings();
}
void MainWindow::SetBusy(bool busy, std::wstring const& message, int percent)
{
// Ignore delayed progress callbacks that arrive after their operation
// has already ended and the command gate returned to Idle.
if (busy && operationGate_.idle()) return;
busy_ = busy;
GlobalProgress().Visibility(busy ? Visibility::Visible : Visibility::Collapsed);
const bool animateIndeterminate = percent < 0 && !ReduceMotionEffective();
GlobalProgress().IsIndeterminate(animateIndeterminate);
if (percent >= 0) GlobalProgress().Value(percent);
else if (!animateIndeterminate) GlobalProgress().Value(50);
if (busy)
{
statusDetail_ = message;
SetSemanticStatus(UiStatusKind::Working, operationGate_.current(), percent);
}
RefreshCommandStates();
}