-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFitWallpaper.cpp
More file actions
1625 lines (1383 loc) · 61.4 KB
/
Copy pathFitWallpaper.cpp
File metadata and controls
1625 lines (1383 loc) · 61.4 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
// to use rand_s()
#define _CRT_RAND_S
//#define _WIN32_WINNT _WIN32_WINNT_WINXP
//#define WDK_NTDDI_VERSION NTDDI_WINXPSP1
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
//#include <opencv2/highgui.hpp>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <VersionHelpers.h>
#include <algorithm>
#include <vector>
#include <math.h>
static constexpr const auto BUSYSTATE_CPU_USAGE_THRESHOLD = 40;
static constexpr const auto BUSYSTATE_CPU_USAGE_CHK_INTVAL = 5;
static constexpr const auto BUSYSTATE_NOT_BUSY = 0;
static constexpr const auto BUSYSTATE_BUSY = 1;
static constexpr const auto PIC_LIST_CHANGED = 0;
static constexpr const auto PIC_LIST_NOT_CHANGED = 1;
static constexpr const auto PROC_WALLPAPER_DONE = 0;
static constexpr const auto PROC_WALLPAPER_DUP_PICTURE = 1;
static constexpr const auto SUPPORTED_IMAGE_EXT = 0;
static constexpr const auto NOT_SUPPORTED_IMAGE_EXT = 1;
static constexpr const auto MIN_EMPTY_SPACE_COLOR = 0;
static constexpr const auto EMPTY_SPACE_COLOR_B = 0;
static constexpr const auto EMPTY_SPACE_COLOR_W = 1;
static constexpr const auto EMPTY_SPACE_COLOR_D = 2;
static constexpr const auto MAX_EMPTY_SPACE_COLOR = 2;
static constexpr const auto MIN_PERIOD_IN_MINUTE = 15;
static constexpr const auto MAX_PERIOD_IN_MINUTE = 1440;
static constexpr const auto MIN_UPSCALE_MODE = 0;
static constexpr const auto UPSCALE_MODE_DONT_UPSCALE = 0;
static constexpr const auto UPSCALE_MODE_UPSCALE_UP_TO_2X = 1;
static constexpr const auto UPSCALE_MODE_UPSCALE_UP_TO_4X = 2;
static constexpr const auto UPSCALE_MODE_UPSCALE_SCR = 3;
static constexpr const auto MAX_UPSCALE_MODE = 3;
static constexpr const auto CONF_DEFAULT_EMPTY_SPACE_COLOR = EMPTY_SPACE_COLOR_D;
static constexpr const auto CONF_DEFAULT_PERIOD_IN_MINUTE = 30;
static constexpr const auto CONF_DEFAULT_UPSCALE_MODE = UPSCALE_MODE_UPSCALE_UP_TO_2X;
static constexpr const auto MAX_CONFIG_FILE_LENGTH = 1536;
static constexpr const auto MAX_PICTURE_NUMBER = 100000;
static constexpr const auto MAX_IMAGE_EXT_LENGTH = 4;
static constexpr const BYTE BOM_UTF8[] = { 0xEF, 0xBB, 0xBF };
static constexpr const ULONGLONG MAX_PICTURE_FILESIZE = 1024ULL * 1024ULL * 128ULL;
static constexpr const char* STR_MAX_PICTURE_FILESIZE = "128MB";
static constexpr const wchar_t* WSTR_PROGRAM_NAME = L"FitWallpaper.exe";
static constexpr const char* STR_WALLPAPER_FNAME_PNG = "wallpaper.png";
static constexpr const wchar_t* WSTR_WALLPAPER_FNAME_PNG = L"wallpaper.png";
static constexpr const char* STR_WALLPAPER_FNAME_JPEG = "wallpaper.jpg";
static constexpr const wchar_t* WSTR_WALLPAPER_FNAME_JPEG = L"wallpaper.jpg";
static constexpr const wchar_t* WSTR_CMDLINE_UNREGISTER = L"/u";
static constexpr const wchar_t* WSTR_CMDLINE_BOOT = L"/boot";
static constexpr const char* STR_CONF_DIR_PICTURE = "dirPicture";
static constexpr const auto LEN_CONF_DIR_PICTURE = 10;
static constexpr const char* STR_CONF_EMPTY_SPACE_COLOR = "emptySpaceColor";
static constexpr const auto LEN_CONF_EMPTY_SPACE_COLOR = 15;
static constexpr const char* STR_CONF_PERIOD_IN_MINUTE = "periodInMinute";
static constexpr const auto LEN_CONF_PERIOD_IN_MINUTE = 14;
static constexpr const char* STR_CONF_UPSCALE_MODE = "upscaleMode";
static constexpr const auto LEN_CONF_UPSCALE_MODE = 11;
static constexpr const char* STR_IMAGE_EXT_LIST[] = { "jpeg", "jpg", "jpe", "png", "bmp", "tif", "tiff" };
static constexpr const wchar_t* WSTR_IMAGE_EXT_LIST[] = { L"jpeg", L"jpg", L"jpe", L"png", L"bmp", L"tif", L"tiff" };
using namespace cv;
using namespace std;
int isSystemBusy();
int updatePictureList(const wchar_t* wDirPicture, wchar_t* picList, int& sizePicList);
int processWallpaper(const wchar_t* picList, const int sizePicList, const bool bPicListChanged, const int emptySpaceColor, const int upscaleMode, const bool bUseJPEGFormat);
void DisplayInfoBoxA(LPCSTR szInfoMsg);
void DisplayErrorBoxW(LPCWSTR wszErrorMsg);
int registerRunAtStartupReg(const wchar_t* wszDirWorking);
int unregisterRunAtStartupReg();
int updateJPEGImportQualityReg();
ULONGLONG getLastChangedReg();
int updateLastChangedReg();
int unregisterKeyFromReg();
int checkDirectory(const wchar_t* dir, const wchar_t* dirName);
int checkFile(const wchar_t* file, const wchar_t* fileName);
int isSupportedImageFile(const wchar_t* imageFileName);
int cvt_utf8_to_wchar(const char* src, const int srcSize, wchar_t* dest, const int destSize);
int cvt_wchar_to_utf8(const wchar_t* src, const int srcSize, char* dest, const int destSize);
int isIllegalCharacterExist(const wchar_t* wstr, const int size);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// require at least Windows XP SP1
if (!IsWindowsXPSP1OrGreater()) {
MessageBoxW(NULL, L"Windows version is too old!\nRequire at least XP SP1!", L"FitWallpaper: Error", MB_ICONERROR | MB_OK);
return -1;
}
// if program run with WSTR_CMDLINE_UNREGISTER(/u)
// try to unregister all registry and exit.
if (wcslen(WSTR_CMDLINE_UNREGISTER) == wcslen(lpCmdLine) &&
0 == wcsncmp(lpCmdLine, WSTR_CMDLINE_UNREGISTER, wcslen(WSTR_CMDLINE_UNREGISTER)))
{
if (-1 == unregisterRunAtStartupReg()) return -1;
if (-1 == unregisterKeyFromReg()) return -1;
return 0;
}
// check FitWallpaper::Running mutex for single instance
const HANDLE hMutexRunning = CreateMutexA(NULL, TRUE, "FitWallpaper::Running");
if (NULL == hMutexRunning) {
DisplayErrorBoxW(L"Failed to create mutex!");
return -1;
}
bool bRunning = false;
if (GetLastError() == ERROR_ALREADY_EXISTS) {
bRunning = true;
CloseHandle(hMutexRunning);
}
wchar_t wDirWorking[MAX_PATH] = L"";
wchar_t wDirPicture[MAX_PATH] = L"";
wchar_t wWallpaperPath[MAX_PATH] = L"";
int emptySpaceColor = CONF_DEFAULT_EMPTY_SPACE_COLOR;
int periodInMinute = CONF_DEFAULT_PERIOD_IN_MINUTE;
int upscaleMode = CONF_DEFAULT_UPSCALE_MODE;
bool bUseJPEGFormat = true;
// Windows 8 or later use PNG format which is natively supported
if (IsWindows8OrGreater()) {
bUseJPEGFormat = false;
}
// check current directory
{
// get program (exe file) location including program file name.
const DWORD lenDirWorking = GetModuleFileNameW(NULL, wDirWorking, MAX_PATH);
// check error or overflow
if (0 == lenDirWorking || MAX_PATH == lenDirWorking) {
DisplayErrorBoxW(L"Failed to get a program location or a program location is too long!");
return -1;
}
// delete characters from end to lastest '\'
// which written as '\\FitWallpaper.exe'
wchar_t* pEnd = wcsrchr(wDirWorking, L'\\');
if (pEnd == NULL) {
DisplayErrorBoxW(L"A current directory is invalid!");
return -1;
}
// check program filename is correct
wchar_t wszInvalidProgramName[128] = L"";
if (-1 == swprintf_s(wszInvalidProgramName,
L"A program filename is incorrect!\n"
L"Correct one is <%s>!",
WSTR_PROGRAM_NAME))
{
DisplayErrorBoxW(L"Failed to create error message say invalid program filename!");
return -1;
}
const size_t lenProgramName = wcslen(WSTR_PROGRAM_NAME);
if (lenProgramName != wcsnlen_s(pEnd + 1, lenProgramName + 1) ||
0 != wcsncmp(pEnd + 1, WSTR_PROGRAM_NAME, lenProgramName)) {
DisplayErrorBoxW(wszInvalidProgramName);
return -1;
}
// fill '\\FitWallpaper.exe' as 0
while (*pEnd != L'\0') {
*pEnd = L'\0';
pEnd++;
}
// check length
if (wcslen(wDirWorking) >= (MAX_PATH - wcslen(WSTR_WALLPAPER_FNAME_JPEG) - 1 - 1)) {
DisplayErrorBoxW(L"A current directory is too long!");
return -1;
}
if (-1 == checkDirectory(wDirWorking, L"current directory")) return -1;
// change current directory to program (exe file) location
if (0 == SetCurrentDirectoryW(wDirWorking)) {
DisplayErrorBoxW(L"Failed to change current directory!");
return -1;
}
wcscat_s(wWallpaperPath, wDirWorking);
wcscat_s(wWallpaperPath, L"\\");
if (bUseJPEGFormat)
wcscat_s(wWallpaperPath, WSTR_WALLPAPER_FNAME_JPEG);
else
wcscat_s(wWallpaperPath, WSTR_WALLPAPER_FNAME_PNG);
}
// update run at startup registry
// only if lpCmdLine is empty and there are no instance running
if (0 == wcslen(lpCmdLine) && !bRunning) {
if (-1 == registerRunAtStartupReg(wDirWorking)) return -1;
DisplayInfoBoxA("Run at startup registry is updated.\nPlease, run a program again if program's location is changed.");
// multi-monitor check
if (1 < GetSystemMetrics(SM_CMONITORS))
DisplayInfoBoxA("This program doesn't support multi-monitor\nYou may continue to use this program\nBut how wallpaper be applied is unpredictable");
// JPEGImportQuality registry check
if (-1 == updateJPEGImportQualityReg()) return -1;
// Theme roaming check
if (IsWindows8OrGreater())
DisplayInfoBoxA(
"You may turn off <Theme roaming> in [Settings App -> User Accounts -> Sync your settings]\n"
"Because there are compression for roamed themes if it exceed a limit");
}
// file operation
{
FILE* fp = NULL;
// create file to stop program (stop.cmd)
fopen_s(&fp, "stop.cmd", "rb");
// if failed to open stop.cmd, make it because it doesn't exist.
if (fp == NULL) {
int err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND) {
fopen_s(&fp, "stop.cmd", "wb");
if (fp == NULL) {
DisplayErrorBoxW(L"Failed to create stop.cmd!");
return -1;
}
const char* szStopCmd =
"@echo off\n"
"echo kill program running\n"
"taskkill /f /im FitWallpaper.exe\n"
"echo remove startup registry\n"
"FitWallpaper.exe /u\n"
"echo press any key to exit\n"
"pause>nul";
if (-1 == fwrite(szStopCmd, sizeof(char), strlen(szStopCmd), fp)) {
fclose(fp);
DisplayErrorBoxW(L"Failed to write stop.cmd!");
return -1;
}
}
else {
DisplayErrorBoxW(L"Failed to open stop.cmd!");
return -1;
}
}
fclose(fp);
// load config file (config.txt)
fopen_s(&fp, "config.txt", "rb");
// if failed to open config.txt, make default config file because it doesn't exist. and exit.
if (fp == NULL) {
int err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND) {
fopen_s(&fp, "config.txt", "wb");
if (fp == NULL) {
DisplayErrorBoxW(L"Failed to create config.txt!");
return -1;
}
if (-1 == fwrite(BOM_UTF8, sizeof(BYTE), 3, fp)) {
fclose(fp);
DisplayErrorBoxW(L"Failed to write config.txt!");
return -1;
}
char szImageExtList[MAX_CONFIG_FILE_LENGTH] = "";
for (const char* szImageExt : STR_IMAGE_EXT_LIST) {
strcat_s(szImageExtList, szImageExt);
strcat_s(szImageExtList, ", ");
}
szImageExtList[strnlen_s(szImageExtList, MAX_CONFIG_FILE_LENGTH) - 1] = '\0';
szImageExtList[strnlen_s(szImageExtList, MAX_CONFIG_FILE_LENGTH) - 1] = '\0';
char szConfDefault[MAX_CONFIG_FILE_LENGTH] = "";
if (-1 == sprintf_s(szConfDefault,
"# Please save this as UTF8 encoding\n"
"# Picture Directory - up to %d Pictures / each file up to %s\n"
"# Support format: %s\n"
"%s = D:\\Pictures\n"
"\n"
"# Fill an empty space with selected color (Default: %d)\n"
"# 0: Black, 1: White, 2: Dominant Color\n"
"%s = %d\n"
"\n"
"# Change picture every X minute(s) [15 ~ 1440] (Default: %d)\n"
"%s = %d\n"
"\n"
"# Upscale mode (Default: %d)\n"
"# 0: Don't upscale\n"
"# 1: Upscale picture up to 2x\n"
"# 2: Upscale picture up to 4x\n"
"# 3: Upscale picture to the screen size\n"
"%s = %d",
MAX_PICTURE_NUMBER, STR_MAX_PICTURE_FILESIZE,
szImageExtList,
STR_CONF_DIR_PICTURE,
CONF_DEFAULT_EMPTY_SPACE_COLOR,
STR_CONF_EMPTY_SPACE_COLOR, CONF_DEFAULT_EMPTY_SPACE_COLOR,
CONF_DEFAULT_PERIOD_IN_MINUTE,
STR_CONF_PERIOD_IN_MINUTE, CONF_DEFAULT_PERIOD_IN_MINUTE,
CONF_DEFAULT_UPSCALE_MODE,
STR_CONF_UPSCALE_MODE, CONF_DEFAULT_UPSCALE_MODE))
{
fclose(fp);
DisplayErrorBoxW(L"Failed to create default config.txt data!");
return -1;
}
if (-1 == fwrite(szConfDefault, sizeof(char), strlen(szConfDefault), fp)) {
fclose(fp);
DisplayErrorBoxW(L"Failed to write config.txt!");
return -1;
}
fclose(fp);
DisplayInfoBoxA("A config.txt is created in current directory!\nPlease, edit it properly and restart a program!");
// exit without error
return 0;
}
else {
DisplayErrorBoxW(L"Failed to open config.txt!");
return -1;
}
}
// read config
char pBuf[MAX_CONFIG_FILE_LENGTH] = "";
size_t rdBytes = fread(pBuf, sizeof(BYTE), MAX_CONFIG_FILE_LENGTH, fp);
fclose(fp);
if (rdBytes >= MAX_CONFIG_FILE_LENGTH) {
DisplayErrorBoxW(L"A config.txt file's size is too big!");
return -1;
}
else if (rdBytes < LEN_CONF_DIR_PICTURE) {
DisplayErrorBoxW(L"A config.txt file's size is too small!");
return -1;
}
char* pStart;
char* pEnd;
char* pCur;
char dirPicture[MAX_PATH] = "";
pCur = &pBuf[0];
if (0 == strncmp((const char*)BOM_UTF8, pCur, 3))
pCur += 3;
pCur--;
do {
// read line
pStart = pCur + 1;
pCur = strchr(pStart, '\r');
if (pCur == NULL) {
pCur = strchr(pStart, '\n');
if (pCur == NULL) {
pCur = strchr(pStart, '\0');
if (pCur == NULL) {
DisplayErrorBoxW(L"A config.txt is damaged!");
return -1;
}
}
}
pEnd = pCur;
if (*pCur == '\r' && *(pCur + 1) == '\n') pCur++;
// trim space and tab
while (*pStart == ' ' || *pStart == '\t') pStart++;
pEnd--;
while (*pEnd == ' ' || *pEnd == '\t') pEnd--;
pEnd++;
// this line is not a comment
if (*pStart != '#' && *pStart != '\0') {
*pEnd = '\0';
const size_t lenCurConf = strlen(pStart);
// dirPicture
if (lenCurConf > LEN_CONF_DIR_PICTURE &&
0 == strncmp(pStart, STR_CONF_DIR_PICTURE, LEN_CONF_DIR_PICTURE))
{
pStart += LEN_CONF_DIR_PICTURE;
while (*pStart == ' ' || *pStart == '\t') pStart++;
if (*pStart != '=') continue;
pStart++;
while (*pStart == ' ' || *pStart == '\t') pStart++;
const size_t lenDirPicture = strnlen_s(pStart, MAX_PATH);
if (lenDirPicture == 0) {
DisplayErrorBoxW(L"A dirPicture value is empty!");
return -1;
}
else if (lenDirPicture >= MAX_PATH) {
DisplayErrorBoxW(L"A dirPicture value's length is too long!");
return -1;
}
else if (0 != memcpy_s(dirPicture, MAX_PATH, pStart, lenDirPicture)) {
DisplayErrorBoxW(L"Failed to get dirPicture value!");
return -1;
}
if (-1 == cvt_utf8_to_wchar(dirPicture, MAX_PATH, wDirPicture, MAX_PATH)) return -1;
}
// emptySpaceColor
else if (lenCurConf > LEN_CONF_EMPTY_SPACE_COLOR &&
0 == strncmp(pStart, STR_CONF_EMPTY_SPACE_COLOR, LEN_CONF_EMPTY_SPACE_COLOR))
{
pStart += LEN_CONF_EMPTY_SPACE_COLOR;
while (*pStart == ' ' || *pStart == '\t') pStart++;
if (*pStart != '=') continue;
pStart++;
while (*pStart == ' ' || *pStart == '\t') pStart++;
const size_t lenEsColor = strnlen_s(pStart, 2);
if (lenEsColor == 0) {
DisplayErrorBoxW(L"A emptySpaceColor value is empty!");
return -1;
}
else if (lenEsColor == 2) {
DisplayErrorBoxW(L"A emptySpaceColor value's length must be 1!");
return -1;
}
emptySpaceColor = *pStart - '0';
if (emptySpaceColor < MIN_EMPTY_SPACE_COLOR || emptySpaceColor > MAX_EMPTY_SPACE_COLOR) {
DisplayErrorBoxW(L"A emptySpaceColor value must be between 0 and 2 inclusive!");
return -1;
}
}
// periodInMinute
else if (lenCurConf > LEN_CONF_PERIOD_IN_MINUTE &&
0 == strncmp(pStart, STR_CONF_PERIOD_IN_MINUTE, LEN_CONF_PERIOD_IN_MINUTE))
{
pStart += LEN_CONF_PERIOD_IN_MINUTE;
while (*pStart == ' ' || *pStart == '\t') pStart++;
if (*pStart != '=') continue;
pStart++;
while (*pStart == ' ' || *pStart == '\t') pStart++;
char szMinute[5] = "";
const size_t lenPeriodInMinute = strnlen_s(pStart, 5);
if (lenPeriodInMinute == 0) {
DisplayErrorBoxW(L"A periodInMinute value is empty!");
return -1;
}
else if (lenPeriodInMinute == 1 || lenPeriodInMinute == 5) {
DisplayErrorBoxW(L"A periodInMinute value's length must be between 2 and 4 inclusive!");
return -1;
}
if (0 != memcpy_s(szMinute, 5, pStart, lenPeriodInMinute)) {
DisplayErrorBoxW(L"Failed to get periodInMinute value!");
return -1;
}
periodInMinute = atoi(szMinute);
if (periodInMinute == 0) {
DisplayErrorBoxW(L"A periodInMinute value is zero or not a number!");
return -1;
}
else if (periodInMinute < MIN_PERIOD_IN_MINUTE || periodInMinute > MAX_PERIOD_IN_MINUTE) {
DisplayErrorBoxW(L"A periodInMinute value must be between 15 and 1440 inclusive!");
return -1;
}
}
// upscaleMode
else if (lenCurConf > LEN_CONF_UPSCALE_MODE &&
0 == strncmp(pStart, STR_CONF_UPSCALE_MODE, LEN_CONF_UPSCALE_MODE))
{
pStart += LEN_CONF_UPSCALE_MODE;
while (*pStart == ' ' || *pStart == '\t') pStart++;
if (*pStart != '=') continue;
pStart++;
while (*pStart == ' ' || *pStart == '\t') pStart++;
const size_t lenUpscaleMode = strnlen_s(pStart, 2);
if (lenUpscaleMode == 0) {
DisplayErrorBoxW(L"A upscaleMode value is empty!");
return -1;
}
else if (lenUpscaleMode == 2) {
DisplayErrorBoxW(L"A upscaleMode value's length must be 1!");
return -1;
}
upscaleMode = *pStart - '0';
if (upscaleMode < MIN_UPSCALE_MODE || upscaleMode > MAX_UPSCALE_MODE) {
DisplayErrorBoxW(L"A upscaleMode value must be between 0 and 3 inclusive!");
return -1;
}
}
*pEnd = '\n';
}
} while (*pCur != '\0');
}
const bool bBootCmd = (wcslen(WSTR_CMDLINE_BOOT) == wcslen(lpCmdLine) &&
0 == wcsncmp(lpCmdLine, WSTR_CMDLINE_BOOT, wcslen(WSTR_CMDLINE_BOOT)));
// if lpCmdLine is file, try to update wallpaper using it and exit
if (0 != wcslen(lpCmdLine) && !bBootCmd) {
// trim cmdLine first
// if filename has space, " is attached on front and end side
// so remove them, too.
wchar_t* pStart = lpCmdLine;
wchar_t* pEnd = pStart + wcslen(lpCmdLine);
while (*pStart == ' ' || *pStart == '\t') pStart++;
if (L'\"' == *pStart) pStart++;
pEnd--;
while (*pEnd == ' ' || *pEnd == '\t') pEnd--;
if (L'\"' == *pEnd) pEnd--;
pEnd++;
*pEnd = L'\0';
// check file
if (MAX_PATH <= wcsnlen_s(pStart, MAX_PATH)) {
DisplayErrorBoxW(L"File in command line is too long or including multiple files!");
return -1;
}
if (-1 == checkFile(pStart, L"picture file in argument")) return -1;
{
int result = isSupportedImageFile(pStart);
if (SUPPORTED_IMAGE_EXT != result) {
if (NOT_SUPPORTED_IMAGE_EXT == result)
DisplayErrorBoxW(L"This file is not supported image file!");
return -1;
}
}
// check FitWallpaper::Processing mutex existance
// to exit when image is processing in another instance
HANDLE hMutexProcessing = CreateMutexA(NULL, TRUE, "FitWallpaper::Processing");
if (NULL == hMutexProcessing) {
DisplayErrorBoxW(L"Failed to create mutex!");
return -1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(hMutexProcessing);
DisplayInfoBoxA("Please retry after a wallpaper is changed! It's soon!");
return 0;
}
CloseHandle(hMutexProcessing);
if (-1 == processWallpaper(pStart, 1, true, emptySpaceColor, upscaleMode, bUseJPEGFormat)) return -1;
// set wallpaper and exit
SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)wWallpaperPath, SPIF_UPDATEINIFILE);
return 0;
}
// check working directory
if (-1 == checkDirectory(wDirPicture, L"picture directory")) return -1;
// allocate picList in heap
HANDLE hDefaultHeap = GetProcessHeap();
wchar_t* picList = nullptr;
int sizePicList = 0;
if (nullptr == hDefaultHeap) {
DisplayErrorBoxW(L"Failed to get default heap handle!");
return -1;
}
picList = (wchar_t*)HeapAlloc(hDefaultHeap, HEAP_ZERO_MEMORY, MAX_PICTURE_NUMBER * MAX_PATH * sizeof(wchar_t));
if (nullptr == picList) {
DisplayErrorBoxW(L"Failed to allocate memory for picture list!");
return -1;
}
// if this instance started while another instance is running
// update wallpaper once and exit
if (bRunning) {
// check FitWallpaper::Processing mutex existance
// to exit when image is processing in another instance
HANDLE hMutexProcessing = CreateMutexA(NULL, TRUE, "FitWallpaper::Processing");
if (NULL == hMutexProcessing) {
DisplayErrorBoxW(L"Failed to create mutex!");
HeapFree(GetProcessHeap(), 0, picList);
return -1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(hMutexProcessing);
HeapFree(GetProcessHeap(), 0, picList);
DisplayInfoBoxA("Please retry after a wallpaper is changed! It's soon!");
return 0;
}
CloseHandle(hMutexProcessing);
if (-1 == updatePictureList(wDirPicture, picList, sizePicList)) {
HeapFree(GetProcessHeap(), 0, picList);
return -1;
}
if (-1 == processWallpaper(picList, sizePicList, true, emptySpaceColor, upscaleMode, bUseJPEGFormat)) {
HeapFree(GetProcessHeap(), 0, picList);
return -1;
}
// set wallpaper and exit
SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)wWallpaperPath, SPIF_UPDATEINIFILE);
HeapFree(GetProcessHeap(), 0, picList);
return 0;
}
// wait 1 minute for system boot complete if this instance run at startup
if (bBootCmd) Sleep(60000);
// check enough time passed from lastChanged
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
const ULONGLONG sysTime = (((ULONGLONG)ft.dwHighDateTime << 32) + ft.dwLowDateTime) / 10000ULL;
const long long period = periodInMinute * 60000LL;
const long long leftTimeToUpdate = period - (long long)(sysTime - getLastChangedReg());
if (leftTimeToUpdate > 0 && leftTimeToUpdate <= period)
Sleep((DWORD)leftTimeToUpdate);
}
while (true) {
// if system is busy, wait 1 minute.
do {
int busyState = isSystemBusy();
if (-1 == busyState) {
HeapFree(GetProcessHeap(), 0, picList);
CloseHandle(hMutexRunning);
return -1;
}
if (BUSYSTATE_NOT_BUSY == busyState) break;
Sleep(60000UL - BUSYSTATE_CPU_USAGE_CHK_INTVAL * 1000UL);
} while (true);
// check FitWallpaper::Processing mutex existance
// to wait image processing is done in another one-time-instance
HANDLE hMutexProcessing = NULL;
while (true) {
hMutexProcessing = CreateMutexA(NULL, TRUE, "FitWallpaper::Processing");
if (NULL == hMutexProcessing) {
DisplayErrorBoxW(L"Failed to create mutex!");
HeapFree(GetProcessHeap(), 0, picList);
CloseHandle(hMutexRunning);
return -1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(hMutexProcessing);
Sleep(3000UL);
}
else {
break;
}
}
// update picList and process wallpaper file
const int bListChanged = updatePictureList(wDirPicture, picList, sizePicList);
if (-1 == bListChanged) break;
bool bPicListChanged = false;
if (PIC_LIST_CHANGED == bListChanged) bPicListChanged = true;
const int bWallpaperProcessed = processWallpaper(picList, sizePicList, bPicListChanged, emptySpaceColor, upscaleMode, bUseJPEGFormat);
if (-1 == bWallpaperProcessed) break;
// close handle which has connection with FitWallpaper::Processing mutex
CloseHandle(hMutexProcessing);
if (PROC_WALLPAPER_DONE == bWallpaperProcessed) {
// set wallpaper
SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)wWallpaperPath, SPIF_UPDATEINIFILE);
// update lastChanged value in registry
if (-1 == updateLastChangedReg()) break;
}
// wait until next update time
Sleep(periodInMinute * 60000UL - BUSYSTATE_CPU_USAGE_CHK_INTVAL * 1000UL);
}
// when program reached here, there were something wrong
// free heap when exit for safety
HeapFree(GetProcessHeap(), 0, picList);
// close handle which has connection with mutex when exit for safety
CloseHandle(hMutexRunning);
return -1;
} // wWinMain
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// return BUSYSTATE_NOT_BUSY (not busy), BUSYSTATE_BUSY (busy) or -1 (error)
int isSystemBusy() {
// on vista or later, check UserNotificationState first.
if (IsWindowsVistaOrGreater()) {
QUERY_USER_NOTIFICATION_STATE userNotiState = QUNS_NOT_PRESENT;
if (S_OK != SHQueryUserNotificationState(&userNotiState)) {
DisplayErrorBoxW(L"SHQueryUserNotificationState failed!");
return -1;
}
// assume that system is busy when it's in fullscreen or PRESENTATION mode, too.
if (userNotiState == QUNS_BUSY ||
userNotiState == QUNS_RUNNING_D3D_FULL_SCREEN ||
userNotiState == QUNS_PRESENTATION_MODE)
return BUSYSTATE_BUSY;
}
// get cpu usage stat before
FILETIME ftIdle0, ftKernel0, ftUser0;
if (0 == GetSystemTimes(&ftIdle0, &ftKernel0, &ftUser0)) {
DisplayErrorBoxW(L"GetSystemTimes failed!");
return -1;
}
const ULONGLONG idle0 = ((ULONGLONG)ftIdle0.dwHighDateTime << 32) + ftIdle0.dwLowDateTime;
const ULONGLONG kernel0 = ((ULONGLONG)ftKernel0.dwHighDateTime << 32) + ftKernel0.dwLowDateTime;
const ULONGLONG user0 = ((ULONGLONG)ftUser0.dwHighDateTime << 32) + ftUser0.dwLowDateTime;
// wait BUSYSTATE_CPU_USAGE_CHK_INTVAL seconds
Sleep(BUSYSTATE_CPU_USAGE_CHK_INTVAL * 1000);
// get cpu usage stat after
FILETIME ftIdle1, ftKernel1, ftUser1;
if (0 == GetSystemTimes(&ftIdle1, &ftKernel1, &ftUser1)) {
DisplayErrorBoxW(L"GetSystemTimes failed!");
return -1;
}
const ULONGLONG idle1 = ((ULONGLONG)ftIdle1.dwHighDateTime << 32) + ftIdle1.dwLowDateTime;
const ULONGLONG kernel1 = ((ULONGLONG)ftKernel1.dwHighDateTime << 32) + ftKernel1.dwLowDateTime;
const ULONGLONG user1 = ((ULONGLONG)ftUser1.dwHighDateTime << 32) + ftUser1.dwLowDateTime;
const ULONGLONG diffIdle = idle1 - idle0;
const ULONGLONG diffKernel = kernel1 - kernel0;
const ULONGLONG diffUser = user1 - user0;
// assume that system is busy if cpu usage is over
// BUSY_CPU_USAGE_THRESHOLD(%) for BUSYSTATE_CPU_USAGE_CHK_INTVAL seconds
if (BUSYSTATE_CPU_USAGE_THRESHOLD < ((diffKernel + diffUser - diffIdle) * 100ULL / (diffKernel + diffUser))) {
return BUSYSTATE_BUSY;
}
// system is not busy
return BUSYSTATE_NOT_BUSY;
} // isSystemBusy
// check picture directory is modified
// if so update picList and sizePicList data
// return PIC_LIST_CHANGED (ok) or -1 (error)
// return PIC_LIST_NOT_CHANGED (no need to update)
int updatePictureList(const wchar_t* wDirPicture, wchar_t* picList, int &sizePicList) {
if (nullptr == wDirPicture || nullptr == picList) {
DisplayErrorBoxW(L"A wDirPicture or picList is null! (updatePictureList)");
return -1;
}
if (-1 == checkDirectory(wDirPicture, L"picture directory")) return -1;
const size_t lenWDirPicture = wcsnlen_s(wDirPicture, MAX_PATH);
if (lenWDirPicture > (MAX_PATH - 3)) {
DisplayErrorBoxW(L"A picture directory path's length is too long!");
return -1;
}
// check picture directory is modified
HANDLE hDir = CreateFileW(wDirPicture, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hDir == INVALID_HANDLE_VALUE) {
DisplayErrorBoxW(L"A picture directory is invalid! (CreateFile)");
return -1;
}
static FILETIME ftWriteBefore = { 0 };
FILETIME ftWrite = { 0 };
if (0 == GetFileTime(hDir, NULL, NULL, &ftWrite)) {
DisplayErrorBoxW(L"Failed to get lastWrite time of a picture directory! (GetFileTime)");
return -1;
}
CloseHandle(hDir);
// compare modified time before after
if (ftWriteBefore.dwHighDateTime == ftWrite.dwHighDateTime
&& ftWriteBefore.dwLowDateTime == ftWrite.dwLowDateTime)
return PIC_LIST_NOT_CHANGED;
// backup changed modified time
ftWriteBefore = ftWrite;
// make find query
wchar_t wszQuery[MAX_PATH] = L"";
wcscat_s(wszQuery, wDirPicture);
wcscat_s(wszQuery, L"\\*");
WIN32_FIND_DATAW wfd;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFileW(wszQuery, &wfd);
if (INVALID_HANDLE_VALUE == hFind) {
DisplayErrorBoxW(L"Failed to get handle from FindFirstFileW!");
return -1;
}
wchar_t* pPicList = picList;
sizePicList = 0;
do {
// check attributes
if (0 != (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
0 != (wfd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ||
// check file extension
SUPPORTED_IMAGE_EXT != isSupportedImageFile(wfd.cFileName) ||
// check filesize
MAX_PICTURE_FILESIZE < (((ULONGLONG)wfd.nFileSizeHigh << 32) + wfd.nFileSizeLow) ||
// check limit of pictures
sizePicList >= MAX_PICTURE_NUMBER)
continue;
const size_t lenWPicFound = wcsnlen_s(wfd.cFileName, MAX_PATH);
if (MAX_PATH > lenWPicFound && (lenWDirPicture + 1 + lenWPicFound) < MAX_PATH) {
memset(pPicList, 0, MAX_PATH * sizeof(wchar_t));
wcscat_s(pPicList, MAX_PATH, wDirPicture);
wcscat_s(pPicList, MAX_PATH, L"\\");
wcscat_s(pPicList, MAX_PATH, wfd.cFileName);
pPicList += MAX_PATH;
sizePicList++;
}
} while (FindNextFileW(hFind, &wfd) != 0);
DWORD dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES) {
DisplayErrorBoxW(L"An error is occured at FindNextFileW!");
return -1;
}
// image file not found
if (sizePicList == 0) {
DisplayErrorBoxW(L"No image file found from picture directory!");
return -1;
}
return PIC_LIST_CHANGED;
} // updatePictureList
// return PROC_WALLPAPER_DUP_PICTURE (no need to update), PROC_WALLPAPER_DONE (ok) or -1 (error)
int processWallpaper(const wchar_t* picList, const int sizePicList, const bool bPicListChanged, const int emptySpaceColor, const int upscaleMode, const bool bUseJPEGFormat) {
if (emptySpaceColor < MIN_EMPTY_SPACE_COLOR || emptySpaceColor > MAX_EMPTY_SPACE_COLOR) {
DisplayErrorBoxW(L"An emptySpaceColor value is incorrect!");
return -1;
}
if (nullptr == picList || sizePicList <= 0 || sizePicList > MAX_PICTURE_NUMBER) {
DisplayErrorBoxW(L"A picList is incorrect!");
return -1;
}
static int lastIdxSelected = -1;
int idxSelected = -1;
if (bPicListChanged) lastIdxSelected = -1;
// if picList data is not changed and sizePicList is only 1
// there are no need to update wallpaper
// because wallpaper which is only one is applied already
else if (1 == sizePicList) {
return PROC_WALLPAPER_DUP_PICTURE;
}
Mat input = Mat();
{
FILE* fp = nullptr;
long long sizePicture = -1;
unsigned int rndNumber = -1;
errno_t err = rand_s(&rndNumber);
if (err != 0) {
DisplayErrorBoxW(L"Failed to call rand_s function!");
return -1;
}
idxSelected = int((double)rndNumber / ((double)UINT_MAX + 1) * sizePicList);
if (idxSelected == lastIdxSelected)
idxSelected = (idxSelected + 1) % sizePicList;
const wchar_t* pPath = picList;
pPath += idxSelected * MAX_PATH;
_wfopen_s(&fp, pPath, L"rb");
if (nullptr == fp) {
DisplayErrorBoxW(L"Failed to open picture file!");
return -1;
}
const int fileno = _fileno(fp);
if (-1 == fileno) {
fclose(fp);
DisplayErrorBoxW(L"Failed to get picture file's descriptor!");
return -1;
}
sizePicture = _filelengthi64(fileno);
if (-1LL == sizePicture) {
fclose(fp);
DisplayErrorBoxW(L"Failed to get picture file's size!");
return -1;
}
else if (MAX_PICTURE_FILESIZE < sizePicture) {
fclose(fp);
DisplayErrorBoxW(L"A picture file's size is too big!");
return -1;
}
vector<BYTE> picData(sizePicture);
const size_t rdBytes = fread(&picData[0], sizeof(BYTE), sizePicture, fp);
fclose(fp);
if (rdBytes != sizePicture) {
DisplayErrorBoxW(L"Failed to read picture file!");
return -1;
}
input = imdecode(move(picData), IMREAD_UNCHANGED);
}
if (input.empty()) {
DisplayErrorBoxW(L"Failed to read image file!");
return -1;
}
// convert to 8 bits color channel
normalize(input, input, 0, UCHAR_MAX, NORM_MINMAX, CV_8U);
// save channel count of input
const int inputChannels = input.channels();
// shrink if need
const int desktop_x = GetSystemMetrics(SM_CXSCREEN);
const int desktop_y = GetSystemMetrics(SM_CYSCREEN);
const double sx = (double)desktop_x / input.cols;
const double sy = (double)desktop_y / input.rows;
// shrink only if scale value < 1.0
if (sx > sy && sy < 1.0)
resize(input, input, Size(), sy, sy, INTER_CUBIC);
else if (sx <= sy && sx < 1.0)
resize(input, input, Size(), sx, sx, INTER_CUBIC);
// fallback empty space color is white
int esColorB = 255, esColorG = 255, esColorR = 255;
// if empty space exist or image has alpha (transparancy) data (BGRA)
// update empty space color
if (input.cols < desktop_x || input.rows < desktop_y || inputChannels == 4) {
if (inputChannels == 4) {
for (int i = 0; i < input.rows; i++) {
for (int j = 0; j < input.cols; j++)
{
Vec4b& v = input.at<Vec4b>(i, j);
if (v[3] == 0) v = Scalar(0, 0, 0, 0);
}
}
}
if (emptySpaceColor == EMPTY_SPACE_COLOR_D) {
Mat m = input.reshape(1, input.rows * input.cols);
m.convertTo(m, CV_32F);
Mat labels, centers;
kmeans(m, 6, labels, TermCriteria(TermCriteria::COUNT | TermCriteria::EPS, 10, 1.0),
1, KMEANS_RANDOM_CENTERS, centers);
int hist[6] = {};
for (int i = 0; i < labels.rows; i++)