Repository navigation
Expand file tree
/
Copy pathTaskManager.cpp
More file actions
2647 lines (2317 loc) · 89.3 KB
/
Copy pathTaskManager.cpp
File metadata and controls
2647 lines (2317 loc) · 89.3 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
#define UNICODE
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#ifndef _WIN32_IE
#define _WIN32_IE 0x0600
#endif
#include <windows.h>
#include <commctrl.h>
#include <shellapi.h>
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
// -----------------------------------------------------------------------------
// Task Manager - native Win32 API, C++11
// Data is stored in tasks.dat beside the executable.
// -----------------------------------------------------------------------------
struct Task
{
std::wstring title;
wchar_t category; // A, B, C, D or E
};
static HINSTANCE g_instance = NULL;
static HWND g_window = NULL;
static HWND g_titleLabel = NULL;
static HWND g_subtitleLabel = NULL;
static HWND g_taskLabel = NULL;
static HWND g_categoryLabel = NULL;
static HWND g_taskEdit = NULL;
static HWND g_categoryCombo = NULL;
static HWND g_addButton = NULL;
static HWND g_legendLabel = NULL;
static HWND g_listCaption = NULL;
static HWND g_list = NULL;
static HWND g_deleteButton = NULL;
static HWND g_saveButton = NULL;
static HWND g_statusLabel = NULL;
static HWND g_settingsButton = NULL;
static HWND g_aboutButton = NULL;
static HWND g_aboutWindow = NULL;
static HWND g_aboutTitleLabel = NULL;
static HWND g_aboutSubtitleLabel = NULL;
static HWND g_aboutDescriptionLabel = NULL;
static HWND g_aboutVersionLabel = NULL;
static HWND g_aboutFooterLabel = NULL;
static HWND g_aboutGithubButton = NULL;
static HWND g_aboutTelegramButton = NULL;
static HICON g_appIconBig = NULL;
static HICON g_appIconSmall = NULL;
static bool g_trayIconAdded = false;
static bool g_trayNoticeShown = false;
static bool g_mainWasMaximized = false;
static UINT g_taskbarCreatedMessage = 0;
static HWND g_settingsWindow = NULL;
static HWND g_editWindow = NULL;
static HWND g_editHeadingLabel = NULL;
static HWND g_editSubheadingLabel = NULL;
static HWND g_editTitleLabel = NULL;
static HWND g_editCategoryLabel = NULL;
static HWND g_editTitleEdit = NULL;
static HWND g_editCategoryCombo = NULL;
static HWND g_editSaveButton = NULL;
static HWND g_editCancelButton = NULL;
static int g_editTaskIndex = -1;
static bool g_mainShuttingDown = false;
static HWND g_settingsHeading = NULL;
static HWND g_settingsSubheading = NULL;
static HWND g_settingsOptionLabel = NULL;
static HWND g_startupStateLabel = NULL;
static HWND g_settingsHintLabel = NULL;
static HWND g_startupToggle = NULL;
static bool g_startupEnabled = false;
static bool g_startupStateKnown = false;
static LONG g_startupLastError = ERROR_SUCCESS;
static HFONT g_font = NULL;
static HFONT g_boldFont = NULL;
static HBRUSH g_backgroundBrush = NULL;
static HBRUSH g_headerBrush = NULL;
static HBRUSH g_whiteBrush = NULL;
static std::vector<Task> g_tasks;
static std::wstring g_dataPath;
static bool g_dirty = false;
static bool g_loadError = false;
static const int ID_TASK_EDIT = 101;
static const int ID_CATEGORY_COMBO = 102;
static const int ID_ADD = 103;
static const int ID_LIST = 104;
static const int ID_DELETE = 105;
static const int ID_SAVE = 106;
static const int ID_SETTINGS = 107;
static const int ID_ABOUT = 108;
static const int ID_TRAY_OPEN = 601;
static const int ID_TRAY_ABOUT = 602;
static const int ID_TRAY_EXIT = 603;
static const int ID_ABOUT_GITHUB = 701;
static const int ID_ABOUT_TELEGRAM = 702;
static const int IDI_APP_RESOURCE = 101;
static const UINT WM_TRAY_CALLBACK = WM_APP + 0x51;
static const int ID_STARTUP_TOGGLE = 301;
static const int ID_EDIT_TITLE = 401;
static const int ID_EDIT_CATEGORY = 402;
static const int ID_EDIT_SAVE = 403;
static const int ID_EDIT_CANCEL = 404;
// A dropdown COMBOBOX HWND must retain enough total height for its list.
// The closed selection field remains visually compact; the extra height is
// used only when the drop-down list is displayed.
static const int CATEGORY_COMBO_WIDTH = 310;
static const int CATEGORY_COMBO_WINDOW_HEIGHT = 210;
static const COLORREF COLOR_BG = RGB(242, 247, 250);
static const COLORREF COLOR_NAVY = RGB(20, 49, 72);
static const COLORREF COLOR_GREEN = RGB(31, 158, 119);
static const COLORREF COLOR_BLUE = RGB(48, 116, 181);
static const COLORREF COLOR_RED = RGB(211, 83, 83);
static const COLORREF COLOR_TEXT = RGB(42, 57, 70);
static const COLORREF COLOR_MUTED = RGB(111, 128, 142);
static void LoadApplicationIcons(HINSTANCE instance)
{
g_appIconBig = reinterpret_cast<HICON>(LoadImageW(
instance, MAKEINTRESOURCEW(IDI_APP_RESOURCE), IMAGE_ICON,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR));
g_appIconSmall = reinterpret_cast<HICON>(LoadImageW(
instance, MAKEINTRESOURCEW(IDI_APP_RESOURCE), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR));
}
static void DestroyApplicationIcons()
{
if (g_appIconBig)
DestroyIcon(g_appIconBig);
if (g_appIconSmall)
DestroyIcon(g_appIconSmall);
g_appIconBig = NULL;
g_appIconSmall = NULL;
}
static void AddTrayIcon(HWND window)
{
if (g_trayIconAdded || !g_appIconSmall)
return;
NOTIFYICONDATAW data;
ZeroMemory(&data, sizeof(data));
data.cbSize = sizeof(data);
data.hWnd = window;
data.uID = 1;
data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
data.uCallbackMessage = WM_TRAY_CALLBACK;
data.hIcon = g_appIconSmall;
lstrcpynW(data.szTip, L"مدیریت کارها", static_cast<int>(sizeof(data.szTip) / sizeof(data.szTip[0])));
if (Shell_NotifyIconW(NIM_ADD, &data))
g_trayIconAdded = true;
}
static void RemoveTrayIcon(HWND window)
{
if (!g_trayIconAdded)
return;
NOTIFYICONDATAW data;
ZeroMemory(&data, sizeof(data));
data.cbSize = sizeof(data);
data.hWnd = window;
data.uID = 1;
Shell_NotifyIconW(NIM_DELETE, &data);
g_trayIconAdded = false;
}
static void ShowTrayNotice(HWND window)
{
if (!g_trayIconAdded || g_trayNoticeShown)
return;
NOTIFYICONDATAW data;
ZeroMemory(&data, sizeof(data));
data.cbSize = sizeof(data);
data.hWnd = window;
data.uID = 1;
data.uFlags = NIF_INFO;
lstrcpynW(data.szInfoTitle, L"مدیریت کارها", static_cast<int>(sizeof(data.szInfoTitle) / sizeof(data.szInfoTitle[0])));
lstrcpynW(data.szInfo,
L"برنامه همچنان در پسزمینه فعال است. برای خروج کامل، روی آیکون کنار ساعت راستکلیک کنید.",
static_cast<int>(sizeof(data.szInfo) / sizeof(data.szInfo[0])));
data.dwInfoFlags = NIIF_INFO;
if (Shell_NotifyIconW(NIM_MODIFY, &data))
g_trayNoticeShown = true;
}
static void ShowMainWindow(HWND window)
{
// Remember whether the main window was maximized before it was hidden
// or minimized to the notification area.
ShowWindow(window, g_mainWasMaximized ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL);
SetForegroundWindow(window);
BringWindowToTop(window);
}
static void ShowTrayContextMenu(HWND window)
{
HMENU menu = CreatePopupMenu();
if (!menu)
return;
AppendMenuW(menu, MF_STRING, ID_TRAY_OPEN, L"باز کردن برنامه");
AppendMenuW(menu, MF_STRING, ID_TRAY_ABOUT, L"درباره برنامه");
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(menu, MF_STRING, ID_TRAY_EXIT, L"خروج کامل");
POINT point;
GetCursorPos(&point);
SetForegroundWindow(window);
TrackPopupMenu(menu, TPM_RIGHTBUTTON | TPM_RIGHTALIGN | TPM_BOTTOMALIGN,
point.x, point.y, 0, window, NULL);
PostMessageW(window, WM_NULL, 0, 0);
DestroyMenu(menu);
}
// Keep the task vector in priority order (A -> E). stable_sort preserves
// the previous order of tasks that belong to the same category.
static void SortTasksByCategory()
{
std::stable_sort(g_tasks.begin(), g_tasks.end(),
[](const Task& left, const Task& right)
{
return left.category < right.category;
});
}
static std::wstring Trim(const std::wstring& value)
{
const std::wstring::size_type first = value.find_first_not_of(L" \t\r\n");
if (first == std::wstring::npos)
return L"";
const std::wstring::size_type last = value.find_last_not_of(L" \t\r\n");
return value.substr(first, last - first + 1);
}
static bool WriteExact(HANDLE file, const void* data, DWORD bytes)
{
const BYTE* current = static_cast<const BYTE*>(data);
DWORD total = 0;
while (total < bytes)
{
DWORD written = 0;
if (!WriteFile(file, current + total, bytes - total, &written, NULL) || written == 0)
return false;
total += written;
}
return true;
}
static bool ReadExact(HANDLE file, void* data, DWORD bytes)
{
BYTE* current = static_cast<BYTE*>(data);
DWORD total = 0;
while (total < bytes)
{
DWORD received = 0;
if (!ReadFile(file, current + total, bytes - total, &received, NULL) || received == 0)
return false;
total += received;
}
return true;
}
static void BuildDataPath()
{
std::vector<wchar_t> buffer(32768, L'\0');
DWORD length = GetModuleFileNameW(NULL, &buffer[0], static_cast<DWORD>(buffer.size()));
if (length == 0 || length >= buffer.size())
{
g_dataPath = L"tasks.dat";
return;
}
std::wstring executablePath(&buffer[0], length);
const std::wstring::size_type slash = executablePath.find_last_of(L"\\/");
if (slash != std::wstring::npos)
executablePath.resize(slash + 1);
else
executablePath.clear();
g_dataPath = executablePath + L"tasks.dat";
}
// Startup is controlled explicitly from the Settings window. The per-user Run
// key does not require administrator privileges.
static const wchar_t* STARTUP_RUN_KEY =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
static const wchar_t* STARTUP_VALUE_NAME = L"PersianWin32TaskManager";
static LONG ReadStartupState(bool* enabled)
{
if (!enabled)
return ERROR_INVALID_PARAMETER;
*enabled = false;
HKEY runKey = NULL;
LONG result = RegOpenKeyExW(
HKEY_CURRENT_USER, STARTUP_RUN_KEY, 0, KEY_QUERY_VALUE, &runKey);
if (result == ERROR_FILE_NOT_FOUND || result == ERROR_PATH_NOT_FOUND)
return ERROR_SUCCESS; // Missing Run key means startup is disabled.
if (result != ERROR_SUCCESS)
return result;
DWORD type = 0;
DWORD size = 0;
result = RegQueryValueExW(
runKey, STARTUP_VALUE_NAME, NULL, &type, NULL, &size);
if (result == ERROR_FILE_NOT_FOUND)
result = ERROR_SUCCESS;
else if (result == ERROR_SUCCESS)
*enabled = true;
RegCloseKey(runKey);
return result;
}
static LONG SetStartupState(bool enabled)
{
HKEY runKey = NULL;
LONG result = ERROR_SUCCESS;
if (enabled)
{
std::vector<wchar_t> pathBuffer(32768, L'\0');
const DWORD pathLength = GetModuleFileNameW(
NULL, &pathBuffer[0], static_cast<DWORD>(pathBuffer.size()));
if (pathLength == 0)
return static_cast<LONG>(GetLastError());
if (pathLength >= pathBuffer.size())
return ERROR_INSUFFICIENT_BUFFER;
const std::wstring executablePath(&pathBuffer[0], pathLength);
const std::wstring command = L"\"" + executablePath + L"\"";
result = RegCreateKeyExW(
HKEY_CURRENT_USER,
STARTUP_RUN_KEY,
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_QUERY_VALUE | KEY_SET_VALUE,
NULL,
&runKey,
NULL);
if (result != ERROR_SUCCESS)
return result;
const DWORD dataSize = static_cast<DWORD>(
(command.size() + 1) * sizeof(wchar_t));
result = RegSetValueExW(
runKey,
STARTUP_VALUE_NAME,
0,
REG_SZ,
reinterpret_cast<const BYTE*>(command.c_str()),
dataSize);
// Verify the value after writing it. Do not show the switch as ON
// unless the exact executable command is present in the registry.
if (result == ERROR_SUCCESS)
{
std::vector<wchar_t> verifyBuffer(command.size() + 2, L'\0');
DWORD verifySize = static_cast<DWORD>(verifyBuffer.size() * sizeof(wchar_t));
DWORD verifyType = 0;
result = RegQueryValueExW(
runKey,
STARTUP_VALUE_NAME,
NULL,
&verifyType,
reinterpret_cast<BYTE*>(&verifyBuffer[0]),
&verifySize);
if (result == ERROR_SUCCESS &&
(verifyType != REG_SZ || std::wstring(&verifyBuffer[0]) != command))
{
result = ERROR_INVALID_DATA;
}
}
RegCloseKey(runKey);
return result;
}
result = RegOpenKeyExW(
HKEY_CURRENT_USER,
STARTUP_RUN_KEY,
0,
KEY_QUERY_VALUE | KEY_SET_VALUE,
&runKey);
if (result == ERROR_FILE_NOT_FOUND || result == ERROR_PATH_NOT_FOUND)
return ERROR_SUCCESS; // Already disabled.
if (result != ERROR_SUCCESS)
return result;
result = RegDeleteValueW(runKey, STARTUP_VALUE_NAME);
if (result == ERROR_FILE_NOT_FOUND)
result = ERROR_SUCCESS; // Idempotent: deleting an absent value is OK.
// Confirm that the value is actually gone before reporting success.
if (result == ERROR_SUCCESS)
{
DWORD type = 0;
DWORD size = 0;
const LONG verifyResult = RegQueryValueExW(
runKey, STARTUP_VALUE_NAME, NULL, &type, NULL, &size);
if (verifyResult == ERROR_SUCCESS)
result = ERROR_GEN_FAILURE;
else if (verifyResult != ERROR_FILE_NOT_FOUND)
result = verifyResult;
}
RegCloseKey(runKey);
return result;
}
static void ShowStartupError(HWND owner, LONG errorCode)
{
wchar_t* systemText = NULL;
const DWORD chars = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
static_cast<DWORD>(errorCode),
0,
reinterpret_cast<LPWSTR>(&systemText),
0,
NULL);
std::wstring message =
L"تغییر تنظیم اجرای خودکار انجام نشد. وضعیت قبلی حفظ شده است.";
if (chars && systemText)
message += L"\n\nجزئیات: " + Trim(systemText);
message += L"\nکد خطا: " + std::to_wstring(errorCode);
if (systemText)
LocalFree(systemText);
MessageBoxW(owner, message.c_str(), L"خطا در تنظیم استارتاپ", MB_OK | MB_ICONERROR);
}
static bool SaveTasks()
{
if (g_dataPath.empty())
BuildDataPath();
HANDLE file = CreateFileW(
g_dataPath.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (file == INVALID_HANDLE_VALUE)
return false;
const char magic[8] = { 'T', 'A', 'S', 'K', 'S', '0', '1', '\0' };
const DWORD count = static_cast<DWORD>(g_tasks.size());
bool ok = WriteExact(file, magic, sizeof(magic)) && WriteExact(file, &count, sizeof(count));
for (size_t i = 0; ok && i < g_tasks.size(); ++i)
{
const DWORD category = static_cast<DWORD>(g_tasks[i].category - L'A');
const DWORD length = static_cast<DWORD>(g_tasks[i].title.size());
if (length > 10000 || category > 4)
{
ok = false;
break;
}
ok = WriteExact(file, &category, sizeof(category)) &&
WriteExact(file, &length, sizeof(length));
if (ok && length > 0)
ok = WriteExact(file, g_tasks[i].title.data(), length * sizeof(wchar_t));
}
if (ok)
ok = FlushFileBuffers(file) != 0;
CloseHandle(file);
if (ok)
g_dirty = false;
return ok;
}
static bool LoadTasks()
{
if (g_dataPath.empty())
BuildDataPath();
HANDLE file = CreateFileW(
g_dataPath.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (file == INVALID_HANDLE_VALUE)
{
const DWORD error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND)
return true; // First launch: no saved file yet.
return false;
}
char magic[8] = { 0 };
DWORD count = 0;
const char expected[8] = { 'T', 'A', 'S', 'K', 'S', '0', '1', '\0' };
bool ok = ReadExact(file, magic, sizeof(magic)) &&
ReadExact(file, &count, sizeof(count)) &&
memcmp(magic, expected, sizeof(expected)) == 0 &&
count <= 10000;
std::vector<Task> loaded;
for (DWORD i = 0; ok && i < count; ++i)
{
DWORD category = 0;
DWORD length = 0;
ok = ReadExact(file, &category, sizeof(category)) &&
ReadExact(file, &length, sizeof(length)) &&
category <= 4 && length > 0 && length <= 10000;
if (!ok)
break;
Task task;
task.category = static_cast<wchar_t>(L'A' + category);
task.title.assign(length, L'\0');
ok = ReadExact(file, &task.title[0], length * sizeof(wchar_t));
if (ok)
{
if (task.title.find(L'\0') != std::wstring::npos)
ok = false;
else
loaded.push_back(task);
}
}
CloseHandle(file);
if (ok)
{
g_tasks.swap(loaded);
SortTasksByCategory();
}
return ok;
}
static COLORREF CategoryTextColor(wchar_t category)
{
switch (category)
{
case L'A': return RGB(190, 61, 61);
case L'B': return RGB(38, 111, 168);
case L'C': return RGB(166, 113, 27);
case L'D': return RGB(111, 83, 158);
default: return RGB(99, 111, 122);
}
}
static COLORREF CategoryBackColor(wchar_t category)
{
switch (category)
{
case L'A': return RGB(255, 235, 235);
case L'B': return RGB(232, 244, 252);
case L'C': return RGB(255, 247, 228);
case L'D': return RGB(243, 238, 251);
default: return RGB(239, 243, 246);
}
}
static std::wstring ToPersianDigits(size_t value)
{
std::wstring digits = std::to_wstring(value);
const wchar_t persianDigits[10] = { L'۰', L'۱', L'۲', L'۳', L'۴', L'۵', L'۶', L'۷', L'۸', L'۹' };
for (size_t i = 0; i < digits.size(); ++i)
{
if (digits[i] >= L'0' && digits[i] <= L'9')
digits[i] = persianDigits[digits[i] - L'0'];
}
return digits;
}
static const wchar_t* CategoryDisplayName(wchar_t category)
{
switch (category)
{
case L'A': return L"الف";
case L'B': return L"ب";
case L'C': return L"ج";
case L'D': return L"د";
default: return L"هـ";
}
}
static void UpdateStatus()
{
if (!g_statusLabel)
return;
std::wstring message;
if (g_loadError)
message = L"فایل ذخیره قبلی قابل خواندن نبود؛ اطلاعات جدید را ذخیره کنید.";
else if (g_dirty)
message = L"تغییرات ذخیره نشده است";
else
message = L"اطلاعات ذخیره شده است";
message += L" • تعداد کارها: ";
message += ToPersianDigits(g_tasks.size());
SetWindowTextW(g_statusLabel, message.c_str());
}
static void UpdateDeleteButton()
{
if (!g_deleteButton || !g_list)
return;
const int selectedCount = static_cast<int>(ListView_GetSelectedCount(g_list));
EnableWindow(g_deleteButton, selectedCount > 0);
}
static void RefreshList()
{
if (!g_list)
return;
// Rebuild the rows as one operation. This prevents ListView from painting
// intermediate, partially rebuilt rows while the backing task vector is
// already in its new sorted order.
SendMessageW(g_list, WM_SETREDRAW, FALSE, 0);
ListView_DeleteAllItems(g_list);
for (size_t i = 0; i < g_tasks.size(); ++i)
{
LVITEMW item;
ZeroMemory(&item, sizeof(item));
item.mask = LVIF_TEXT;
item.iItem = static_cast<int>(i);
item.iSubItem = 0;
item.pszText = const_cast<LPWSTR>(g_tasks[i].title.c_str());
const int row = ListView_InsertItem(g_list, &item);
if (row >= 0)
{
// Set the label explicitly after insertion as well. This avoids
// relying on the initial LVITEM text pointer for the first column.
ListView_SetItemText(
g_list, row, 0, const_cast<LPWSTR>(g_tasks[i].title.c_str()));
const wchar_t* categoryText = CategoryDisplayName(g_tasks[i].category);
ListView_SetItemText(g_list, row, 1, const_cast<LPWSTR>(categoryText));
}
}
// A full rebuild invalidates the old row selection. Explicitly clear it
// so a newly inserted first row is not accidentally painted as selected.
ListView_SetItemState(g_list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED);
SendMessageW(g_list, WM_SETREDRAW, TRUE, 0);
RedrawWindow(g_list, NULL, NULL,
RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
UpdateDeleteButton();
UpdateStatus();
}
static HWND CreateLabel(HWND parent, const wchar_t* text, DWORD style, int id)
{
HWND control = CreateWindowExW(
WS_EX_RTLREADING,
L"STATIC",
text,
WS_CHILD | WS_VISIBLE | style,
0, 0, 10, 10,
parent,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),
g_instance,
NULL);
if (control && g_font)
SendMessageW(control, WM_SETFONT, reinterpret_cast<WPARAM>(g_font), TRUE);
return control;
}
static HWND CreateActionButton(HWND parent, const wchar_t* text, int id)
{
HWND control = CreateWindowExW(
0,
L"BUTTON",
text,
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 10, 10,
parent,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),
g_instance,
NULL);
if (control && g_font)
SendMessageW(control, WM_SETFONT, reinterpret_cast<WPARAM>(g_font), TRUE);
return control;
}
static void MarkDirty(); // Implemented with the main task-editing commands below.
static void LayoutEditWindow(HWND window)
{
RECT client;
GetClientRect(window, &client);
const int width = client.right - client.left;
const int pad = 28;
const int fieldWidth = width - 2 * pad;
if (g_editHeadingLabel)
MoveWindow(g_editHeadingLabel, pad, 10, fieldWidth, 30, TRUE);
if (g_editSubheadingLabel)
MoveWindow(g_editSubheadingLabel, pad, 42, fieldWidth, 20, TRUE);
if (g_editTitleLabel)
MoveWindow(g_editTitleLabel, pad, 91, fieldWidth, 21, TRUE);
if (g_editTitleEdit)
MoveWindow(g_editTitleEdit, pad, 116, fieldWidth, 36, TRUE);
if (g_editCategoryLabel)
MoveWindow(g_editCategoryLabel, pad, 171, fieldWidth, 21, TRUE);
if (g_editCategoryCombo)
MoveWindow(g_editCategoryCombo, pad, 196, fieldWidth,
CATEGORY_COMBO_WINDOW_HEIGHT, TRUE);
const int buttonWidth = 132;
const int buttonY = 420;
if (g_editSaveButton)
MoveWindow(g_editSaveButton, width - pad - buttonWidth,
buttonY, buttonWidth, 38, TRUE);
if (g_editCancelButton)
MoveWindow(g_editCancelButton, width - pad - 2 * buttonWidth - 12,
buttonY, buttonWidth, 38, TRUE);
}
static void SaveEditedTask(HWND window)
{
if (g_editTaskIndex < 0 ||
static_cast<size_t>(g_editTaskIndex) >= g_tasks.size())
{
MessageBoxW(window, L"کار موردنظر برای ویرایش پیدا نشد.",
L"خطا در ویرایش", MB_OK | MB_ICONERROR);
DestroyWindow(window);
return;
}
const int length = GetWindowTextLengthW(g_editTitleEdit);
if (length <= 0)
{
MessageBoxW(window, L"عنوان کار نمیتواند خالی باشد.",
L"ویرایش کار", MB_OK | MB_ICONINFORMATION);
SetFocus(g_editTitleEdit);
return;
}
std::vector<wchar_t> buffer(static_cast<size_t>(length) + 1, L'\0');
GetWindowTextW(g_editTitleEdit, &buffer[0], length + 1);
const std::wstring title = Trim(&buffer[0]);
if (title.empty())
{
MessageBoxW(window, L"عنوان کار نمیتواند خالی باشد.",
L"ویرایش کار", MB_OK | MB_ICONINFORMATION);
SetFocus(g_editTitleEdit);
return;
}
const int selectedCategory = static_cast<int>(
SendMessageW(g_editCategoryCombo, CB_GETCURSEL, 0, 0));
if (selectedCategory < 0 || selectedCategory > 4)
{
MessageBoxW(window, L"لطفاً یک دستهبندی معتبر انتخاب کنید.",
L"ویرایش کار", MB_OK | MB_ICONINFORMATION);
SetFocus(g_editCategoryCombo);
return;
}
Task& task = g_tasks[static_cast<size_t>(g_editTaskIndex)];
const wchar_t category = static_cast<wchar_t>(L'A' + selectedCategory);
const bool changed = (task.title != title || task.category != category);
if (changed)
{
task.title = title;
task.category = category;
SortTasksByCategory();
MarkDirty();
RefreshList();
}
DestroyWindow(window);
}
static LRESULT CALLBACK EditWindowProc(
HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
g_editWindow = window;
g_editHeadingLabel = CreateLabel(
window, L"ویرایش کار", SS_RIGHT, 501);
g_editSubheadingLabel = CreateLabel(
window, L"عنوان و دستهبندی کار را تغییر دهید.", SS_RIGHT, 502);
g_editTitleLabel = CreateLabel(
window, L"عنوان کار", SS_RIGHT, 503);
g_editCategoryLabel = CreateLabel(
window, L"دستهبندی", SS_RIGHT, 504);
g_editTitleEdit = CreateWindowExW(
WS_EX_CLIENTEDGE | WS_EX_RTLREADING,
L"EDIT", L"",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | ES_RIGHT,
0, 0, 10, 10, window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(ID_EDIT_TITLE)),
g_instance, NULL);
if (g_editTitleEdit)
SendMessageW(g_editTitleEdit, EM_SETLIMITTEXT, 10000, 0);
g_editCategoryCombo = CreateWindowExW(
WS_EX_CLIENTEDGE | WS_EX_RTLREADING,
L"COMBOBOX", L"",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL,
0, 0, CATEGORY_COMBO_WIDTH, CATEGORY_COMBO_WINDOW_HEIGHT,
window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(ID_EDIT_CATEGORY)),
g_instance, NULL);
const wchar_t* categories[5] = {
L"الف ـ در صورت انجام ندادن، پیامد شدید",
L"ب ـ انجام آن سودمند است؛ بدون پیامد شدید",
L"ج ـ در صورت انجام ندادن، پیامد جزئی",
L"د ـ کماهمیت و مناسب واگذاری به دیگران",
L"هـ ـ بدون ضرورت یا اهمیت"
};
if (g_editCategoryCombo)
{
if (g_font)
SendMessageW(g_editCategoryCombo, WM_SETFONT,
reinterpret_cast<WPARAM>(g_font), TRUE);
for (int i = 0; i < 5; ++i)
{
const LRESULT added = SendMessageW(
g_editCategoryCombo, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(categories[i]));
if (added == CB_ERR || added == CB_ERRSPACE)
{
MessageBoxW(window, L"بارگذاری دستهبندیها ناموفق بود.",
L"خطا", MB_OK | MB_ICONERROR);
break;
}
}
SendMessageW(g_editCategoryCombo, CB_SETITEMHEIGHT,
static_cast<WPARAM>(-1), 34);
SendMessageW(g_editCategoryCombo, CB_SETITEMHEIGHT, 0, 32);
SendMessageW(g_editCategoryCombo, CB_SETMINVISIBLE, 5, 0);
SendMessageW(g_editCategoryCombo, CB_SETDROPPEDWIDTH, 430, 0);
}
g_editSaveButton = CreateWindowExW(
0, L"BUTTON", L"ذخیره تغییرات",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
0, 0, 10, 10, window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(ID_EDIT_SAVE)),
g_instance, NULL);
g_editCancelButton = CreateWindowExW(
0, L"BUTTON", L"انصراف",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
0, 0, 10, 10, window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(ID_EDIT_CANCEL)),
g_instance, NULL);
HWND controls[] = {
g_editTitleEdit, g_editSaveButton, g_editCancelButton
};
for (size_t i = 0; i < sizeof(controls) / sizeof(controls[0]); ++i)
{
if (controls[i] && g_font)
SendMessageW(controls[i], WM_SETFONT,
reinterpret_cast<WPARAM>(g_font), TRUE);
}
if (g_editTaskIndex >= 0 &&
static_cast<size_t>(g_editTaskIndex) < g_tasks.size())
{
const Task& task = g_tasks[static_cast<size_t>(g_editTaskIndex)];
SetWindowTextW(g_editTitleEdit, task.title.c_str());
const int categoryIndex = static_cast<int>(task.category - L'A');
SendMessageW(g_editCategoryCombo, CB_SETCURSEL,
(categoryIndex >= 0 && categoryIndex < 5) ? categoryIndex : 0, 0);
}
else
{
SendMessageW(g_editCategoryCombo, CB_SETCURSEL, 0, 0);
}
LayoutEditWindow(window);
return 0;
}
case WM_SIZE:
LayoutEditWindow(window);
return 0;
case WM_ERASEBKGND:
{
RECT rect;
GetClientRect(window, &rect);
FillRect(reinterpret_cast<HDC>(wParam), &rect, g_backgroundBrush);
return 1;
}
case WM_PAINT:
{
PAINTSTRUCT paint;
HDC dc = BeginPaint(window, &paint);
RECT client;
GetClientRect(window, &client);
RECT header = { 0, 0, client.right, 72 };
FillRect(dc, &header, g_headerBrush);
HBRUSH accentBrush = CreateSolidBrush(COLOR_GREEN);
RECT accent = { 0, 0, 6, 72 };
FillRect(dc, &accent, accentBrush);
DeleteObject(accentBrush);
HPEN borderPen = CreatePen(PS_SOLID, 1, RGB(225, 233, 239));
HGDIOBJ oldPen = SelectObject(dc, borderPen);
HGDIOBJ oldBrush = SelectObject(dc, g_whiteBrush);
RoundRect(dc, 18, 84, client.right - 18, client.bottom - 18, 12, 12);
SelectObject(dc, oldBrush);
SelectObject(dc, oldPen);
DeleteObject(borderPen);
EndPaint(window, &paint);
return 0;
}
case WM_CTLCOLORSTATIC:
{
HDC dc = reinterpret_cast<HDC>(wParam);
HWND control = reinterpret_cast<HWND>(lParam);
SetBkMode(dc, TRANSPARENT);
if (control == g_editHeadingLabel)
{
SetTextColor(dc, RGB(255, 255, 255));
return reinterpret_cast<LRESULT>(g_headerBrush);
}
if (control == g_editSubheadingLabel)
{
SetTextColor(dc, RGB(205, 222, 234));
return reinterpret_cast<LRESULT>(g_headerBrush);
}
SetTextColor(dc, COLOR_TEXT);
return reinterpret_cast<LRESULT>(g_whiteBrush);
}
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
{