Repository navigation
Expand file tree
/
Copy pathSettingsDialog.cpp
More file actions
1284 lines (1171 loc) · 54.2 KB
/
Copy pathSettingsDialog.cpp
File metadata and controls
1284 lines (1171 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "SettingsDialog.h"
#include <commctrl.h>
#include <prsht.h>
#include <shobjidl.h>
#include <string>
#include <vector>
#include "Accent.h"
#include "Common.h"
#include "Log.h"
#include "LockScreen.h"
#include "Wallhaven.h"
#include "Wallpaper.h"
#include "resource.h"
#pragma comment(lib, "comctl32.lib")
namespace {
constexpr int kMaxIntervalMinutes = 7 * 24 * 60; // one week
// Pages only ever touch this staged copy; it is committed by the caller after
// the sheet reports OK, so a validation failure on a later page cannot leave
// half-applied settings behind.
Settings g_edit;
bool g_editAutoStart = false;
HINSTANCE g_instance = nullptr;
std::vector<MonitorEntry> g_monitors;
std::vector<Collection> g_collections;
bool g_sheetCentered = false;
// The API key lives on the Search page but the Source page needs it to load
// collections, so the Source page reads the live control rather than the staged
// copy (which is only filled in when the user accepts the sheet).
HWND g_searchPage = nullptr;
HWND g_sourcePage = nullptr;
// ------------------------------------------------------------ small helpers
int ComboAdd(HWND combo, const wchar_t* text, LPARAM data)
{
int index = static_cast<int>(SendMessageW(combo, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(text)));
if (index >= 0)
SendMessageW(combo, CB_SETITEMDATA, static_cast<WPARAM>(index), data);
return index;
}
void ComboSelectByData(HWND combo, LPARAM data)
{
int count = static_cast<int>(SendMessageW(combo, CB_GETCOUNT, 0, 0));
for (int i = 0; i < count; ++i) {
if (static_cast<LPARAM>(SendMessageW(combo, CB_GETITEMDATA,
static_cast<WPARAM>(i), 0)) == data) {
SendMessageW(combo, CB_SETCURSEL, static_cast<WPARAM>(i), 0);
return;
}
}
SendMessageW(combo, CB_SETCURSEL, 0, 0);
}
LPARAM ComboSelectedData(HWND combo, LPARAM fallback)
{
int selected = static_cast<int>(SendMessageW(combo, CB_GETCURSEL, 0, 0));
if (selected == CB_ERR)
return fallback;
LRESULT data = SendMessageW(combo, CB_GETITEMDATA, static_cast<WPARAM>(selected), 0);
return data == CB_ERR ? fallback : static_cast<LPARAM>(data);
}
// LB_GETTEXT has no length argument, so the size must be asked for first.
// LB_GETTEXTLEN may over-report, so the result is trimmed to what was written.
std::wstring ListBoxText(HWND list, int index)
{
int length = static_cast<int>(SendMessageW(list, LB_GETTEXTLEN,
static_cast<WPARAM>(index), 0));
if (length <= 0)
return {};
std::wstring text(static_cast<size_t>(length) + 1, L'\0');
int written = static_cast<int>(SendMessageW(list, LB_GETTEXT,
static_cast<WPARAM>(index), reinterpret_cast<LPARAM>(&text[0])));
text.resize(static_cast<size_t>(written < 0 ? 0 : written));
return text;
}
// capacity is the number of characters wanted; the buffer adds room for the
// terminator so nothing is truncated one character early.
std::wstring GetDlgText(HWND dlg, int id, size_t capacity)
{
std::wstring text(capacity + 1, L'\0');
int length = GetDlgItemTextW(dlg, id, &text[0], static_cast<int>(capacity + 1));
text.resize(static_cast<size_t>(length < 0 ? 0 : length));
return text;
}
// The property sheet is positioned relative to its owner, which is the hidden
// 0x0 tray window at the origin, so it has to be centred by hand. The first
// PSN_SETACTIVE is the earliest point where the sheet has its final size.
void CenterSheetOnce(HWND page)
{
if (g_sheetCentered)
return;
g_sheetCentered = true;
HWND sheet = GetParent(page);
RECT rect;
if (!GetWindowRect(sheet, &rect))
return;
POINT cursor;
GetCursorPos(&cursor);
MONITORINFO info = { sizeof(info) };
if (!GetMonitorInfoW(MonitorFromPoint(cursor, MONITOR_DEFAULTTOPRIMARY), &info))
return;
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
SetWindowPos(sheet, nullptr,
info.rcWork.left + (info.rcWork.right - info.rcWork.left - width) / 2,
info.rcWork.top + (info.rcWork.bottom - info.rcWork.top - height) / 2,
0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
void AcceptPage(HWND dlg)
{
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, PSNRET_NOERROR);
}
// Keeps the sheet open and the user on this page.
void RejectPage(HWND dlg, const wchar_t* message, int focusId)
{
MessageBoxW(dlg, message, L"WallpaperChanger", MB_OK | MB_ICONWARNING);
if (focusId)
SetFocus(GetDlgItem(dlg, focusId));
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE);
}
// Defined with the Wallpaper page; the Source page needs it too.
std::wstring BrowseForFolder(HWND owner, const std::wstring& initial);
// A settings file the user chose to import. Returned to the caller, which does
// the actual replacing: the dialog only ever edits a staged copy.
std::wstring g_importFrom;
// Common file dialog for a single .json file. Returns an empty string when the
// user cancels. `saving` picks the Save flavour rather than Open.
std::wstring BrowseForSettingsFile(HWND owner, bool saving)
{
IFileDialog* dialog = nullptr;
const CLSID which = saving ? CLSID_FileSaveDialog : CLSID_FileOpenDialog;
if (FAILED(CoCreateInstance(which, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog))))
return {};
std::wstring chosen;
COMDLG_FILTERSPEC filters[] = {
{ L"Settings file", L"*.json" },
{ L"All files", L"*.*" },
};
dialog->SetFileTypes(ARRAYSIZE(filters), filters);
dialog->SetDefaultExtension(L"json");
dialog->SetFileName(L"wallpaperchanger-settings.json");
DWORD options = 0;
if (SUCCEEDED(dialog->GetOptions(&options)))
dialog->SetOptions(options | FOS_FORCEFILESYSTEM
| (saving ? FOS_OVERWRITEPROMPT : FOS_FILEMUSTEXIST));
if (SUCCEEDED(dialog->Show(owner))) {
IShellItem* result = nullptr;
if (SUCCEEDED(dialog->GetResult(&result))) {
PWSTR path = nullptr;
if (SUCCEEDED(result->GetDisplayName(SIGDN_FILESYSPATH, &path))) {
chosen = path;
CoTaskMemFree(path);
}
result->Release();
}
}
dialog->Release();
return chosen;
}
int IndexOfValue(const wchar_t* const* values, int count, const std::wstring& value)
{
for (int i = 0; i < count; ++i) {
if (value == values[i])
return i;
}
return 0;
}
// ------------------------------------------------------------- Search page
// Asked once per settings session, so someone who already runs with sketchy
// content on is never nagged about it.
bool g_sketchyConfirmed = false;
// The key that has already been checked against wallhaven. Seeded with the
// saved one so pressing OK without touching it costs no request.
std::wstring g_checkedApiKey;
// Wallhaven serves NSFW only to an authenticated account, so without a key the
// option cannot work at all. Rather than let it be ticked and then refused on
// Apply, it is greyed out until a key is typed, and follows the field live.
void UpdateNsfwAvailability(HWND dlg)
{
bool haveKey = !GetDlgText(dlg, IDC_APIKEY, 128).empty();
EnableWindow(GetDlgItem(dlg, IDC_PUR_NSFW), haveKey);
if (haveKey || !IsDlgButtonChecked(dlg, IDC_PUR_NSFW))
return;
// Clearing the key takes NSFW with it. Leaving nothing ticked would only
// fail on Apply, so fall back to SFW rather than to an invalid page.
CheckDlgButton(dlg, IDC_PUR_NSFW, BST_UNCHECKED);
if (!IsDlgButtonChecked(dlg, IDC_PUR_SFW) && !IsDlgButtonChecked(dlg, IDC_PUR_SKETCHY))
CheckDlgButton(dlg, IDC_PUR_SFW, BST_CHECKED);
}
INT_PTR CALLBACK SearchPageProc(HWND dlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_COMMAND:
if (LOWORD(wParam) == IDC_APIKEY && HIWORD(wParam) == EN_CHANGE) {
UpdateNsfwAvailability(dlg);
break;
}
// Turning sketchy content on is a deliberate choice, not a checkbox to
// brush past. NSFW is gated behind needing an API key, but wallhaven
// serves sketchy to guests, so nothing else would stop it.
if (LOWORD(wParam) == IDC_PUR_SKETCHY
&& HIWORD(wParam) == BN_CLICKED
&& IsDlgButtonChecked(dlg, IDC_PUR_SKETCHY)
&& !g_sketchyConfirmed
&& g_edit.purity[1] != L'1') {
int answer = MessageBoxW(dlg,
L"\"Sketchy\" includes suggestive and revealing wallpapers, which may not be "
L"what you want appearing on your desktop unannounced.\n\n"
L"Turn it on?",
L"WallpaperChanger", MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2);
if (answer == IDYES)
g_sketchyConfirmed = true;
else
CheckDlgButton(dlg, IDC_PUR_SKETCHY, BST_UNCHECKED);
return TRUE;
}
break;
case WM_INITDIALOG: {
g_searchPage = dlg;
SetDlgItemTextW(dlg, IDC_QUERY, g_edit.query.c_str());
SetDlgItemTextW(dlg, IDC_APIKEY, g_edit.apiKey.c_str());
CheckDlgButton(dlg, IDC_CAT_GENERAL, g_edit.categories[0] == L'1' ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_CAT_ANIME, g_edit.categories[1] == L'1' ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_CAT_PEOPLE, g_edit.categories[2] == L'1' ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PUR_SFW, g_edit.purity[0] == L'1' ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PUR_SKETCHY, g_edit.purity[1] == L'1' ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PUR_NSFW, g_edit.purity[2] == L'1' ? BST_CHECKED : BST_UNCHECKED);
UpdateNsfwAvailability(dlg);
HWND ratios = GetDlgItem(dlg, IDC_RATIOS);
for (int i = 0; i < kRatioCount; ++i)
ComboAdd(ratios, kRatioLabels[i], i);
ComboSelectByData(ratios, IndexOfValue(kRatioValues, kRatioCount, g_edit.ratios));
HWND sorting = GetDlgItem(dlg, IDC_SORTING);
for (int i = 0; i < kSortingCount; ++i)
ComboAdd(sorting, kSortingLabels[i], i);
ComboSelectByData(sorting, IndexOfValue(kSortingValues, kSortingCount, g_edit.sorting));
return TRUE;
}
case WM_NOTIFY: {
NMHDR* header = reinterpret_cast<NMHDR*>(lParam);
if (header->code == PSN_SETACTIVE) {
CenterSheetOnce(dlg);
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, 0);
return TRUE;
}
if (header->code == PSN_APPLY) {
std::wstring query = GetDlgText(dlg, IDC_QUERY, 512);
std::wstring apiKey = GetDlgText(dlg, IDC_APIKEY, 128);
std::wstring categories, purity;
categories += IsDlgButtonChecked(dlg, IDC_CAT_GENERAL) ? L'1' : L'0';
categories += IsDlgButtonChecked(dlg, IDC_CAT_ANIME) ? L'1' : L'0';
categories += IsDlgButtonChecked(dlg, IDC_CAT_PEOPLE) ? L'1' : L'0';
purity += IsDlgButtonChecked(dlg, IDC_PUR_SFW) ? L'1' : L'0';
purity += IsDlgButtonChecked(dlg, IDC_PUR_SKETCHY) ? L'1' : L'0';
purity += IsDlgButtonChecked(dlg, IDC_PUR_NSFW) ? L'1' : L'0';
if (categories == L"000") {
RejectPage(dlg, L"Select at least one category.", IDC_CAT_GENERAL);
return TRUE;
}
if (purity == L"000") {
RejectPage(dlg, L"Select at least one purity level.", IDC_PUR_SFW);
return TRUE;
}
if (purity[2] == L'1' && apiKey.empty()) {
RejectPage(dlg, L"NSFW purity requires a Wallhaven API key.", IDC_APIKEY);
return TRUE;
}
// Verify a key the user has just typed, so a typo shows up here
// instead of as a failed change an hour later. Only an outright
// rejection stops the page: if the check could not be made at all,
// being offline must not lock anyone out of their own settings.
// A key that has sat in the settings file for months may have been
// revoked since, so switching NSFW on re-checks it even when the
// key itself was not touched.
bool nsfwNewlyOn = purity[2] == L'1' && g_edit.purity[2] != L'1';
if (!apiKey.empty() && (apiKey != g_checkedApiKey || nsfwNewlyOn)) {
ApiKeyStatus status = ApiKeyStatus::Unknown;
HCURSOR previous = SetCursor(LoadCursorW(nullptr, IDC_WAIT));
try {
WallhavenClient client;
status = client.CheckApiKey(apiKey);
} catch (...) {
// No session; nothing can be concluded about the key.
}
SetCursor(previous);
if (status == ApiKeyStatus::Rejected) {
RejectPage(dlg, L"Wallhaven rejected this API key. Check it on your "
L"wallhaven.cc account settings page.", IDC_APIKEY);
return TRUE;
}
g_checkedApiKey = apiKey;
}
int sortIndex = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_SORTING), 0));
if (kSortingValues[sortIndex] == std::wstring(L"relevance") && query.empty()) {
RejectPage(dlg, L"Sorting by relevance needs a search query.", IDC_QUERY);
return TRUE;
}
g_edit.query = query;
g_edit.apiKey = apiKey;
g_edit.categories = categories;
g_edit.purity = purity;
g_edit.ratios = kRatioValues[ComboSelectedData(GetDlgItem(dlg, IDC_RATIOS), 0)];
g_edit.sorting = kSortingValues[sortIndex];
AcceptPage(dlg);
return TRUE;
}
break;
}
}
return FALSE;
}
// ------------------------------------------------------------- Source page
void FillCollectionCombo(HWND dlg, long long selectedId)
{
HWND combo = GetDlgItem(dlg, IDC_COLLECTIONS);
SendMessageW(combo, CB_RESETCONTENT, 0, 0);
for (size_t i = 0; i < g_collections.size(); ++i) {
std::wstring label = g_collections[i].label + L" ("
+ std::to_wstring(g_collections[i].count) + L")";
// The index is stored, not the id: item data is only pointer-sized.
ComboAdd(combo, label.c_str(), static_cast<LPARAM>(i));
}
for (size_t i = 0; i < g_collections.size(); ++i) {
if (g_collections[i].id == selectedId) {
ComboSelectByData(combo, static_cast<LPARAM>(i));
return;
}
}
if (!g_collections.empty())
SendMessageW(combo, CB_SETCURSEL, 0, 0);
}
void UpdateSourceEnabled(HWND dlg)
{
BOOL useCollection = IsDlgButtonChecked(dlg, IDC_SRC_COLLECTION) ? TRUE : FALSE;
EnableWindow(GetDlgItem(dlg, IDC_COLL_OWNER), useCollection);
EnableWindow(GetDlgItem(dlg, IDC_COLLECTIONS), useCollection);
EnableWindow(GetDlgItem(dlg, IDC_REFRESH_COLLS), useCollection);
BOOL useFolder = IsDlgButtonChecked(dlg, IDC_SRC_FOLDER) ? TRUE : FALSE;
EnableWindow(GetDlgItem(dlg, IDC_LOCAL_FOLDER), useFolder);
EnableWindow(GetDlgItem(dlg, IDC_LOCAL_BROWSE), useFolder);
}
void LoadCollections(HWND dlg)
{
// Read the key the user may have just typed, not the staged copy, which is
// only filled in when the sheet is accepted.
std::wstring apiKey = g_searchPage ? GetDlgText(g_searchPage, IDC_APIKEY, 128)
: g_edit.apiKey;
if (apiKey.empty()) {
SetDlgItemTextW(dlg, IDC_COLL_STATUS, L"Enter your API key on the Search tab first.");
return;
}
std::wstring owner = GetDlgText(dlg, IDC_COLL_OWNER, 64);
if (owner.empty()) {
SetDlgItemTextW(dlg, IDC_COLL_STATUS, L"Enter your Wallhaven user name first.");
return;
}
HCURSOR previous = SetCursor(LoadCursorW(nullptr, IDC_WAIT));
SetDlgItemTextW(dlg, IDC_COLL_STATUS, L"Loading...");
try {
WallhavenClient client;
g_collections = client.ListCollections(apiKey);
FillCollectionCombo(dlg, g_edit.collectionId);
// A wrong user name still returns HTTP 200 with nothing in it, so check
// it here instead of leaving the user to discover it as a failed change.
Settings probe = g_edit;
probe.apiKey = apiKey;
probe.collectionOwner = owner;
int selected = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_COLLECTIONS), -1));
if (selected >= 0 && selected < static_cast<int>(g_collections.size()))
probe.collectionId = g_collections[selected].id;
std::wstring status = std::to_wstring(g_collections.size()) + L" collection(s) found.";
if (probe.collectionId != 0 && !client.VerifyCollectionOwner(probe))
status += L"\r\nBut '" + owner + L"' does not seem to own it - check the name.";
SetDlgItemTextW(dlg, IDC_COLL_STATUS, status.c_str());
} catch (const AppError& e) {
SetDlgItemTextW(dlg, IDC_COLL_STATUS, e.message.c_str());
} catch (const std::exception&) {
// An exception escaping a dialog proc would take the process with it.
SetDlgItemTextW(dlg, IDC_COLL_STATUS, L"Could not read the response from Wallhaven.");
}
SetCursor(previous);
}
INT_PTR CALLBACK SourcePageProc(HWND dlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG:
g_sourcePage = dlg;
CheckRadioButton(dlg, IDC_SRC_SEARCH, IDC_SRC_FOLDER,
g_edit.source == WallpaperSource::Collection ? IDC_SRC_COLLECTION
: g_edit.source == WallpaperSource::Folder ? IDC_SRC_FOLDER
: IDC_SRC_SEARCH);
SetDlgItemTextW(dlg, IDC_LOCAL_FOLDER, g_edit.localFolder.c_str());
SetDlgItemTextW(dlg, IDC_COLL_OWNER, g_edit.collectionOwner.c_str());
if (!g_edit.collectionLabel.empty()) {
HWND combo = GetDlgItem(dlg, IDC_COLLECTIONS);
ComboAdd(combo, g_edit.collectionLabel.c_str(), 0);
SendMessageW(combo, CB_SETCURSEL, 0, 0);
}
UpdateSourceEnabled(dlg);
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_SRC_SEARCH:
case IDC_SRC_COLLECTION:
case IDC_SRC_FOLDER:
// The folder radio is separated from the other two by intervening
// WS_GROUP controls, so the three are not one auto-radio group and
// Windows will not clear across them. Enforce it here.
CheckRadioButton(dlg, IDC_SRC_SEARCH, IDC_SRC_FOLDER, LOWORD(wParam));
UpdateSourceEnabled(dlg);
return TRUE;
case IDC_LOCAL_BROWSE: {
std::wstring chosen = BrowseForFolder(dlg, GetDlgText(dlg, IDC_LOCAL_FOLDER, MAX_PATH));
if (!chosen.empty())
SetDlgItemTextW(dlg, IDC_LOCAL_FOLDER, chosen.c_str());
return TRUE;
}
case IDC_REFRESH_COLLS:
g_edit.collectionOwner = GetDlgText(dlg, IDC_COLL_OWNER, 64);
LoadCollections(dlg);
return TRUE;
}
break;
case WM_NOTIFY: {
NMHDR* header = reinterpret_cast<NMHDR*>(lParam);
if (header->code == PSN_SETACTIVE) {
CenterSheetOnce(dlg);
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, 0);
return TRUE;
}
if (header->code == PSN_APPLY) {
bool useCollection = IsDlgButtonChecked(dlg, IDC_SRC_COLLECTION) != 0;
bool useFolder = IsDlgButtonChecked(dlg, IDC_SRC_FOLDER) != 0;
std::wstring owner = GetDlgText(dlg, IDC_COLL_OWNER, 64);
std::wstring folder = GetDlgText(dlg, IDC_LOCAL_FOLDER, MAX_PATH);
if (useFolder && folder.empty()) {
RejectPage(dlg, L"Choose the folder to take wallpapers from.", IDC_LOCAL_BROWSE);
return TRUE;
}
if (useCollection) {
if (owner.empty()) {
RejectPage(dlg, L"Enter the Wallhaven user name that owns the collection.",
IDC_COLL_OWNER);
return TRUE;
}
int selected = static_cast<int>(ComboSelectedData(
GetDlgItem(dlg, IDC_COLLECTIONS), -1));
if (selected < 0 || selected >= static_cast<int>(g_collections.size())) {
// Nothing was loaded this session; keep whatever was saved before.
if (g_edit.collectionId == 0) {
RejectPage(dlg, L"Choose a collection (press Load first).",
IDC_REFRESH_COLLS);
return TRUE;
}
} else {
g_edit.collectionId = g_collections[selected].id;
g_edit.collectionLabel = g_collections[selected].label;
}
}
g_edit.source = useCollection ? WallpaperSource::Collection
: useFolder ? WallpaperSource::Folder
: WallpaperSource::Search;
g_edit.collectionOwner = owner;
g_edit.localFolder = folder;
AcceptPage(dlg);
return TRUE;
}
break;
}
}
return FALSE;
}
// ----------------------------------------------------------- Schedule page
// The hotkey control and RegisterHotKey use different bit values for the
// same modifiers, so both directions need translating.
BYTE ModifiersToHotkeyFlags(unsigned int modifiers)
{
BYTE flags = 0;
if (modifiers & MOD_SHIFT) flags |= HOTKEYF_SHIFT;
if (modifiers & MOD_CONTROL) flags |= HOTKEYF_CONTROL;
if (modifiers & MOD_ALT) flags |= HOTKEYF_ALT;
return flags;
}
unsigned int HotkeyFlagsToModifiers(BYTE flags)
{
unsigned int modifiers = 0;
if (flags & HOTKEYF_SHIFT) modifiers |= MOD_SHIFT;
if (flags & HOTKEYF_CONTROL) modifiers |= MOD_CONTROL;
if (flags & HOTKEYF_ALT) modifiers |= MOD_ALT;
return modifiers;
}
void UpdateIntervalEnabled(HWND dlg)
{
BOOL enabled = IsDlgButtonChecked(dlg, IDC_AUTO_ENABLE) ? TRUE : FALSE;
EnableWindow(GetDlgItem(dlg, IDC_INTERVAL), enabled);
EnableWindow(GetDlgItem(dlg, IDC_INTERVAL_SPIN), enabled);
}
INT_PTR CALLBACK SchedulePageProc(HWND dlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
HWND spin = GetDlgItem(dlg, IDC_INTERVAL_SPIN);
SendMessageW(spin, UDM_SETBUDDY,
reinterpret_cast<WPARAM>(GetDlgItem(dlg, IDC_INTERVAL)), 0);
SendMessageW(spin, UDM_SETRANGE32, 1, kMaxIntervalMinutes);
SendMessageW(spin, UDM_SETPOS32, 0,
g_edit.intervalMinutes > 0 ? g_edit.intervalMinutes : 60);
CheckDlgButton(dlg, IDC_AUTO_ENABLE, g_edit.intervalMinutes > 0 ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_ON_UNLOCK, g_edit.changeOnUnlock ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PREFER_FAST, g_edit.preferFast ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PREFETCH, g_edit.prefetchNext ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_AUTOSTART, g_editAutoStart ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_SKIP_BUSY, g_edit.skipWhenBusy ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_SFW_PRESENTING, g_edit.sfwWhilePresenting ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_PAUSE_BATTERY, g_edit.pauseOnBattery ? BST_CHECKED : BST_UNCHECKED);
SetDlgItemInt(dlg, IDC_BATTERY_THRESHOLD, g_edit.batteryThreshold, FALSE);
SetDlgItemInt(dlg, IDC_STARTUP_DELAY, g_edit.startupDelaySeconds, FALSE);
UpdateIntervalEnabled(dlg);
HWND hotkey = GetDlgItem(dlg, IDC_HOTKEY);
// A bare key or a Shift-only combination would hijack normal typing.
SendMessageW(hotkey, HKM_SETRULES, HKCOMB_NONE | HKCOMB_S,
MAKELPARAM(HOTKEYF_CONTROL | HOTKEYF_ALT, 0));
SendMessageW(hotkey, HKM_SETHOTKEY,
MAKEWORD(g_edit.hotkeyVirtualKey, ModifiersToHotkeyFlags(g_edit.hotkeyModifiers)), 0);
return TRUE;
}
case WM_COMMAND:
if (LOWORD(wParam) == IDC_AUTO_ENABLE) {
UpdateIntervalEnabled(dlg);
return TRUE;
}
break;
case WM_NOTIFY: {
NMHDR* header = reinterpret_cast<NMHDR*>(lParam);
if (header->code == PSN_SETACTIVE) {
CenterSheetOnce(dlg);
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, 0);
return TRUE;
}
if (header->code == PSN_APPLY) {
BOOL translated = FALSE;
int value = static_cast<int>(GetDlgItemInt(dlg, IDC_INTERVAL, &translated, FALSE));
int minutes = 0;
if (IsDlgButtonChecked(dlg, IDC_AUTO_ENABLE)) {
if (!translated || value < 1) {
RejectPage(dlg, L"Enter how many minutes between changes.", IDC_INTERVAL);
return TRUE;
}
minutes = value > kMaxIntervalMinutes ? kMaxIntervalMinutes : value;
}
WORD packed = static_cast<WORD>(SendMessageW(GetDlgItem(dlg, IDC_HOTKEY),
HKM_GETHOTKEY, 0, 0));
unsigned int hotkeyVk = LOBYTE(packed);
unsigned int hotkeyMods = HotkeyFlagsToModifiers(HIBYTE(packed));
if (hotkeyVk != 0 && hotkeyMods == 0) {
RejectPage(dlg, L"The hotkey needs at least one of Ctrl, Alt or Shift.", IDC_HOTKEY);
return TRUE;
}
if (hotkeyVk == VK_F12) {
RejectPage(dlg, L"F12 is reserved by the debugger and cannot be used.", IDC_HOTKEY);
return TRUE;
}
BOOL batteryOk = FALSE;
int threshold = static_cast<int>(GetDlgItemInt(dlg, IDC_BATTERY_THRESHOLD, &batteryOk, FALSE));
if (!batteryOk || threshold < 0 || threshold > 100)
threshold = 20;
g_edit.intervalMinutes = minutes;
g_edit.changeOnUnlock = IsDlgButtonChecked(dlg, IDC_ON_UNLOCK) != 0;
g_edit.preferFast = IsDlgButtonChecked(dlg, IDC_PREFER_FAST) != 0;
g_edit.prefetchNext = IsDlgButtonChecked(dlg, IDC_PREFETCH) != 0;
g_edit.skipWhenBusy = IsDlgButtonChecked(dlg, IDC_SKIP_BUSY) != 0;
g_edit.sfwWhilePresenting = IsDlgButtonChecked(dlg, IDC_SFW_PRESENTING) != 0;
g_edit.pauseOnBattery = IsDlgButtonChecked(dlg, IDC_PAUSE_BATTERY) != 0;
g_edit.batteryThreshold = threshold;
BOOL delayOk = FALSE;
int delay = static_cast<int>(GetDlgItemInt(dlg, IDC_STARTUP_DELAY, &delayOk, FALSE));
g_edit.startupDelaySeconds = (delayOk && delay >= 0 && delay <= 600) ? delay : 0;
g_editAutoStart = IsDlgButtonChecked(dlg, IDC_AUTOSTART) != 0;
g_edit.hotkeyVirtualKey = hotkeyVk;
g_edit.hotkeyModifiers = hotkeyMods;
AcceptPage(dlg);
return TRUE;
}
break;
}
}
return FALSE;
}
// ---------------------------------------------------------- Wallpaper page
std::wstring BrowseForFolder(HWND owner, const std::wstring& initial)
{
IFileDialog* dialog = nullptr;
if (FAILED(CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dialog))))
return {};
std::wstring chosen;
DWORD options = 0;
if (SUCCEEDED(dialog->GetOptions(&options)))
dialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
if (!initial.empty()) {
IShellItem* item = nullptr;
if (SUCCEEDED(SHCreateItemFromParsingName(initial.c_str(), nullptr, IID_PPV_ARGS(&item)))) {
dialog->SetFolder(item);
item->Release();
}
}
if (SUCCEEDED(dialog->Show(owner))) {
IShellItem* result = nullptr;
if (SUCCEEDED(dialog->GetResult(&result))) {
PWSTR path = nullptr;
if (SUCCEEDED(result->GetDisplayName(SIGDN_FILESYSPATH, &path))) {
chosen = path;
CoTaskMemFree(path);
}
result->Release();
}
}
dialog->Release();
return chosen;
}
// The folder belongs to both "save every wallpaper" and the tray's "Save this
// one", so it stays settable whether or not automatic saving is on. Tying it to
// the checkbox meant anyone who only wanted the occasional manual save could
// not choose where it went.
INT_PTR CALLBACK WallpaperPageProc(HWND dlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
HWND monitors = GetDlgItem(dlg, IDC_MONITOR);
ComboAdd(monitors, L"All monitors", -1);
for (size_t i = 0; i < g_monitors.size(); ++i)
ComboAdd(monitors, g_monitors[i].Describe(static_cast<int>(i)).c_str(),
static_cast<LPARAM>(i));
LPARAM selected = -1;
for (size_t i = 0; i < g_monitors.size(); ++i) {
if (_wcsicmp(g_monitors[i].devicePath.c_str(), g_edit.monitorDevicePath.c_str()) == 0) {
selected = static_cast<LPARAM>(i);
break;
}
}
ComboSelectByData(monitors, selected);
if (g_monitors.size() < 2)
EnableWindow(monitors, FALSE);
HWND fit = GetDlgItem(dlg, IDC_FIT_MODE);
for (int i = 0; i < kFitCount; ++i)
ComboAdd(fit, kFitLabels[i], i);
ComboSelectByData(fit, g_edit.fitMode);
CheckDlgButton(dlg, IDC_SAVE_ENABLE, g_edit.saveEnabled ? BST_CHECKED : BST_UNCHECKED);
std::wstring folder = g_edit.saveFolder.empty() ? DefaultSaveFolder() : g_edit.saveFolder;
SetDlgItemTextW(dlg, IDC_SAVE_FOLDER, folder.c_str());
CheckDlgButton(dlg, IDC_PER_MONITOR, g_edit.perMonitorDifferent ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_LOCK_SCREEN, g_edit.setLockScreen ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_MATCH_ACCENT, g_edit.matchAccentColor ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dlg, IDC_SHOW_THUMBS, g_edit.showThumbnails ? BST_CHECKED : BST_UNCHECKED);
SetDlgItemInt(dlg, IDC_HISTORY_SIZE, g_edit.historySize, FALSE);
// These need more than one screen, or an OS feature that may be absent.
if (g_monitors.size() < 2)
EnableWindow(GetDlgItem(dlg, IDC_PER_MONITOR), FALSE);
if (!AccentControlAvailable())
EnableWindow(GetDlgItem(dlg, IDC_MATCH_ACCENT), FALSE);
if (!LockScreenAvailable())
EnableWindow(GetDlgItem(dlg, IDC_LOCK_SCREEN), FALSE);
return TRUE;
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_SAVE_BROWSE: {
std::wstring current = GetDlgText(dlg, IDC_SAVE_FOLDER, MAX_PATH);
std::wstring chosen = BrowseForFolder(dlg, current);
if (!chosen.empty())
SetDlgItemTextW(dlg, IDC_SAVE_FOLDER, chosen.c_str());
return TRUE;
}
}
break;
case WM_NOTIFY: {
NMHDR* header = reinterpret_cast<NMHDR*>(lParam);
if (header->code == PSN_SETACTIVE) {
CenterSheetOnce(dlg);
SetWindowLongPtrW(dlg, DWLP_MSGRESULT, 0);
return TRUE;
}
if (header->code == PSN_APPLY) {
// With no monitor list (COM unavailable) the combo is meaningless,
// so leave whatever the user configured earlier alone.
if (!g_monitors.empty()) {
int selected = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_MONITOR), -1));
g_edit.monitorDevicePath.clear();
if (selected >= 0 && selected < static_cast<int>(g_monitors.size()))
g_edit.monitorDevicePath = g_monitors[selected].devicePath;
}
g_edit.fitMode = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_FIT_MODE), 4));
g_edit.saveEnabled = IsDlgButtonChecked(dlg, IDC_SAVE_ENABLE) != 0;
g_edit.saveFolder = GetDlgText(dlg, IDC_SAVE_FOLDER, MAX_PATH);
g_edit.perMonitorDifferent = IsDlgButtonChecked(dlg, IDC_PER_MONITOR) != 0;
g_edit.setLockScreen = IsDlgButtonChecked(dlg, IDC_LOCK_SCREEN) != 0;
g_edit.showThumbnails = IsDlgButtonChecked(dlg, IDC_SHOW_THUMBS) != 0;
BOOL historyOk = FALSE;
int history = static_cast<int>(GetDlgItemInt(dlg, IDC_HISTORY_SIZE, &historyOk, FALSE));
g_edit.historySize = (historyOk && history >= 2 && history <= kMaxHistoryEntries)
? history : 10;
// Reading the current accent is harmless and has to happen while it
// is still the user's own colour, so it stays here. Putting the
// colour BACK is a system change and must not happen from a page
// that a later page can still veto, or that Cancel can undo - the
// caller does it once the sheet is actually accepted.
bool wantAccent = IsDlgButtonChecked(dlg, IDC_MATCH_ACCENT) != 0;
// Only ever capture when nothing is stored yet. A later page can
// reject the sheet after this one has already run, and on the next
// attempt the accent in force would be the app's own tint - capturing
// that would overwrite the user's real colour and lose it for good.
if (wantAccent && !g_edit.matchAccentColor && !g_edit.savedAccentValid) {
AccentSnapshot snapshot;
if (!CaptureAccent(snapshot)) {
RejectPage(dlg, L"Your current accent colour could not be read, so it "
L"could not be restored later.", IDC_MATCH_ACCENT);
return TRUE;
}
g_edit.savedAccentValid = true;
g_edit.savedAccentStart = snapshot.startColor;
g_edit.savedAccentColor = snapshot.accentColor;
}
g_edit.matchAccentColor = wantAccent;
if (g_edit.saveEnabled && g_edit.saveFolder.empty()) {
RejectPage(dlg, L"Choose a folder for saved wallpapers.", IDC_SAVE_BROWSE);
return TRUE;
}
AcceptPage(dlg);
return TRUE;
}
break;
}
}
return FALSE;
}
// ----------------------------------------------------------- Profiles page
// Pulls the search settings out of the live controls on the other pages.
// Saving a profile has to see what the user has typed right now, not the staged
// copy, which is only refreshed when the whole sheet is accepted.
void HarvestSearchIntoEdit()
{
if (g_searchPage) {
g_edit.query = GetDlgText(g_searchPage, IDC_QUERY, 512);
g_edit.apiKey = GetDlgText(g_searchPage, IDC_APIKEY, 128);
std::wstring categories, purity;
categories += IsDlgButtonChecked(g_searchPage, IDC_CAT_GENERAL) ? L'1' : L'0';
categories += IsDlgButtonChecked(g_searchPage, IDC_CAT_ANIME) ? L'1' : L'0';
categories += IsDlgButtonChecked(g_searchPage, IDC_CAT_PEOPLE) ? L'1' : L'0';
purity += IsDlgButtonChecked(g_searchPage, IDC_PUR_SFW) ? L'1' : L'0';
purity += IsDlgButtonChecked(g_searchPage, IDC_PUR_SKETCHY) ? L'1' : L'0';
purity += IsDlgButtonChecked(g_searchPage, IDC_PUR_NSFW) ? L'1' : L'0';
if (categories != L"000")
g_edit.categories = categories;
if (purity != L"000")
g_edit.purity = purity;
g_edit.ratios = kRatioValues[ComboSelectedData(GetDlgItem(g_searchPage, IDC_RATIOS), 0)];
g_edit.sorting = kSortingValues[ComboSelectedData(GetDlgItem(g_searchPage, IDC_SORTING), 0)];
}
if (g_sourcePage) {
bool useCollection = IsDlgButtonChecked(g_sourcePage, IDC_SRC_COLLECTION) != 0;
bool useFolder = IsDlgButtonChecked(g_sourcePage, IDC_SRC_FOLDER) != 0;
g_edit.source = useCollection ? WallpaperSource::Collection
: useFolder ? WallpaperSource::Folder
: WallpaperSource::Search;
g_edit.collectionOwner = GetDlgText(g_sourcePage, IDC_COLL_OWNER, 64);
g_edit.localFolder = GetDlgText(g_sourcePage, IDC_LOCAL_FOLDER, MAX_PATH);
int selected = static_cast<int>(ComboSelectedData(
GetDlgItem(g_sourcePage, IDC_COLLECTIONS), -1));
if (selected >= 0 && selected < static_cast<int>(g_collections.size())) {
g_edit.collectionId = g_collections[selected].id;
g_edit.collectionLabel = g_collections[selected].label;
}
}
}
// Rebuilds the list and both schedule combos from g_edit.profiles.
void RefreshProfileControls(HWND dlg)
{
HWND list = GetDlgItem(dlg, IDC_PROFILE_LIST);
int selected = static_cast<int>(SendMessageW(list, LB_GETCURSEL, 0, 0));
SendMessageW(list, LB_RESETCONTENT, 0, 0);
for (const Profile& profile : g_edit.profiles)
SendMessageW(list, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(profile.name.c_str()));
if (selected >= 0 && selected < static_cast<int>(g_edit.profiles.size()))
SendMessageW(list, LB_SETCURSEL, static_cast<WPARAM>(selected), 0);
for (int id : { IDC_DAY_PROFILE, IDC_NIGHT_PROFILE }) {
HWND combo = GetDlgItem(dlg, id);
LPARAM previous = ComboSelectedData(combo, -1);
SendMessageW(combo, CB_RESETCONTENT, 0, 0);
ComboAdd(combo, L"(none)", -1);
for (size_t i = 0; i < g_edit.profiles.size(); ++i)
ComboAdd(combo, g_edit.profiles[i].name.c_str(), static_cast<LPARAM>(i));
ComboSelectByData(combo, previous);
}
bool haveProfiles = !g_edit.profiles.empty();
EnableWindow(GetDlgItem(dlg, IDC_PROFILE_DELETE), haveProfiles);
BOOL scheduled = IsDlgButtonChecked(dlg, IDC_SCHEDULE_ENABLE) ? TRUE : FALSE;
for (int id : { IDC_DAY_PROFILE, IDC_DAY_HOUR, IDC_NIGHT_PROFILE, IDC_NIGHT_HOUR })
EnableWindow(GetDlgItem(dlg, id), scheduled && haveProfiles);
}
INT_PTR CALLBACK ProfilesPageProc(HWND dlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
CheckDlgButton(dlg, IDC_SCHEDULE_ENABLE, g_edit.scheduleEnabled ? BST_CHECKED : BST_UNCHECKED);
SetDlgItemInt(dlg, IDC_DAY_HOUR, g_edit.dayStartHour, FALSE);
SetDlgItemInt(dlg, IDC_NIGHT_HOUR, g_edit.nightStartHour, FALSE);
RefreshProfileControls(dlg);
ComboSelectByData(GetDlgItem(dlg, IDC_DAY_PROFILE), g_edit.dayProfile);
ComboSelectByData(GetDlgItem(dlg, IDC_NIGHT_PROFILE), g_edit.nightProfile);
return TRUE;
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_SCHEDULE_ENABLE:
RefreshProfileControls(dlg);
return TRUE;
case IDC_PROFILE_ADD: {
std::wstring name = GetDlgText(dlg, IDC_PROFILE_NAME, 64);
if (name.empty()) {
MessageBoxW(dlg, L"Give the profile a name first.", L"WallpaperChanger",
MB_OK | MB_ICONWARNING);
return TRUE;
}
if (g_edit.profiles.size() >= kMaxProfiles) {
MessageBoxW(dlg, L"That is as many profiles as this can hold.",
L"WallpaperChanger", MB_OK | MB_ICONWARNING);
return TRUE;
}
HarvestSearchIntoEdit();
// The Source page's own checks do not run when a profile is saved
// from here, so a profile could otherwise capture a source it is
// impossible to fetch from.
if (g_edit.source == WallpaperSource::Folder && g_edit.localFolder.empty()) {
MessageBoxW(dlg, L"Choose the folder on the Source tab before saving this "
L"as a profile.", L"WallpaperChanger", MB_OK | MB_ICONWARNING);
return TRUE;
}
if (g_edit.source == WallpaperSource::Collection
&& (g_edit.collectionOwner.empty() || g_edit.collectionId == 0)) {
MessageBoxW(dlg, L"Choose a collection on the Source tab before saving this "
L"as a profile.", L"WallpaperChanger", MB_OK | MB_ICONWARNING);
return TRUE;
}
// Saving over an existing name replaces it, which is what someone
// reusing a name almost always means.
Profile captured = g_edit.CaptureProfile(name);
bool replaced = false;
for (Profile& existing : g_edit.profiles) {
if (_wcsicmp(existing.name.c_str(), name.c_str()) == 0) {
existing = captured;
replaced = true;
break;
}
}
if (!replaced)
g_edit.profiles.push_back(captured);
SetDlgItemTextW(dlg, IDC_PROFILE_NAME, L"");
RefreshProfileControls(dlg);
return TRUE;
}
case IDC_PROFILE_DELETE: {
HWND list = GetDlgItem(dlg, IDC_PROFILE_LIST);
int selected = static_cast<int>(SendMessageW(list, LB_GETCURSEL, 0, 0));
if (selected < 0 || selected >= static_cast<int>(g_edit.profiles.size()))
return TRUE;
// The combos are only read at PSN_APPLY, so take what the user has
// chosen right now before renumbering, or their choice is lost.
int liveDay = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_DAY_PROFILE), -1));
int liveNight = static_cast<int>(ComboSelectedData(GetDlgItem(dlg, IDC_NIGHT_PROFILE), -1));
g_edit.dayProfile = liveDay;
g_edit.nightProfile = liveNight;
g_edit.profiles.erase(g_edit.profiles.begin() + selected);
// Indexes shift, so anything pointing past the hole has to move too.
auto fix = [&](int& index) {
if (index == selected) index = -1;
else if (index > selected) --index;
};
fix(g_edit.activeProfile);
fix(g_edit.dayProfile);
fix(g_edit.nightProfile);
RefreshProfileControls(dlg);
ComboSelectByData(GetDlgItem(dlg, IDC_DAY_PROFILE), g_edit.dayProfile);
ComboSelectByData(GetDlgItem(dlg, IDC_NIGHT_PROFILE), g_edit.nightProfile);
return TRUE;
}
case IDC_EXPORT_SETTINGS: {
std::wstring target = BrowseForSettingsFile(dlg, true);
if (target.empty())
return TRUE;
// Exports what is saved on disk, not the half-edited sheet, so what
// comes out is a state the app has actually been running with.
if (CopyFileW(SettingsFilePath().c_str(), target.c_str(), FALSE))
MessageBoxW(dlg, (L"Settings written to:\n" + target).c_str(),
L"WallpaperChanger", MB_OK | MB_ICONINFORMATION);
else
MessageBoxW(dlg, L"Could not write that file.", L"WallpaperChanger",
MB_OK | MB_ICONWARNING);
return TRUE;
}
case IDC_IMPORT_SETTINGS: {
std::wstring source = BrowseForSettingsFile(dlg, false);
if (source.empty())
return TRUE;
// Check it parses before offering to replace anything.
Settings probe;
std::vector<WallpaperSlot> probeHistory;
if (!LoadSettingsFrom(source, probe, probeHistory)) {
MessageBoxW(dlg, L"That file is not a WallpaperChanger settings file.",