Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
461 lines (405 loc) · 12.5 KB
/
Copy pathmain.cpp
File metadata and controls
461 lines (405 loc) · 12.5 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
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <string>
#include <cstdio>
#include <cwchar>
#include "resource.h"
// Configs
static std::wstring g_targetDir = L"";
static DWORD g_intervalSec = 180;
static bool g_paused = false;
static HWND g_hwnd = nullptr;
static std::wstring g_iniPath = L"";
#define WM_TRAYICON (WM_APP + 1)
#define IDM_TOGGLE_PAUSE 1001
#define IDM_EXIT 1002
#define IDM_SHOW_STATUS 1003
#define IDM_RECONFIG 1004
#define TRAY_UID 1
#define TIMER_KEEPALIVE 1
// Path tools
static std::wstring GetIniPath()
{
wchar_t appdata[MAX_PATH] = {};
if (FAILED(SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, 0, appdata)))
return L"";
std::wstring dir = std::wstring(appdata) + L"\\KeepDiskAlive";
CreateDirectoryW(dir.c_str(), nullptr);
return dir + L"\\config.ini";
}
static std::wstring NormalizeTarget(const std::wstring& input)
{
std::wstring s = input;
size_t b = s.find_first_not_of(L" \t\r\n");
size_t e = s.find_last_not_of(L" \t\r\n");
if (b == std::wstring::npos) return L"";
s = s.substr(b, e - b + 1);
if (s.size() == 1 && iswalpha(s[0]))
s += L":\\";
else if (s.size() == 2 && iswalpha(s[0]) && s[1] == L':')
s += L'\\';
else if (s.size() >= 2 && iswalpha(s[0]) && s[1] == L':')
{
if (s.back() != L'\\' && s.back() != L'/') s += L'\\';
}
else
{
if (s.back() != L'\\' && s.back() != L'/') s += L'\\';
}
return s;
}
// rw Config files
static bool LoadConfig()
{
g_iniPath = GetIniPath();
if (g_iniPath.empty()) return false;
wchar_t target[512] = {};
GetPrivateProfileStringW(L"Config", L"Target", L"", target, 512, g_iniPath.c_str());
if (target[0] == 0) return false;
std::wstring norm = NormalizeTarget(target);
if (norm.empty()) return false;
g_targetDir = norm;
g_intervalSec = GetPrivateProfileIntW(L"Config", L"IntervalSec", 180, g_iniPath.c_str());
if (g_intervalSec < 10) g_intervalSec = 10;
return true;
}
static void SaveConfig()
{
if (g_iniPath.empty()) return;
WritePrivateProfileStringW(L"Config", L"Target", g_targetDir.c_str(), g_iniPath.c_str());
wchar_t buf[32];
swprintf_s(buf, L"%lu", g_intervalSec);
WritePrivateProfileStringW(L"Config", L"IntervalSec", buf, g_iniPath.c_str());
}
// Ask user for config in console
static bool AskUserForConfig(bool firstTime)
{
wprintf(L"\n=== Disk KeepAlive %ls ===\n", firstTime ? L"Setting" : L"Resetting");
wprintf(L"Current: Disk=%ls Interval=%lu s\n\n",
g_targetDir.empty() ? L"(none)" : g_targetDir.c_str(), g_intervalSec);
wprintf(L"Enter a disk letter (like D, D:\\ or D:\\data): ");
wchar_t buf[512] = {};
if (!fgetws(buf, 512, stdin))
return false;
std::wstring target = NormalizeTarget(buf);
if (target.empty())
{
wprintf(L"You entered air, cancelled.\n");
return false;
}
if (target.size() >= 2 && target[1] == L':')
{
wchar_t root[4] = { target[0], L':', L'\\', 0 };
if (GetDriveTypeW(root) == DRIVE_NO_ROOT_DIR)
{
wprintf(L"This disk does not exist, cancelled.\n", root);
return false;
}
}
wprintf(L"Enter a check interval (in sec, press Enter to use the default %lu, minimum 10): ", g_intervalSec);
DWORD newInterval = g_intervalSec;
if (fgetws(buf, 512, stdin))
{
DWORD sec = (DWORD)_wtoi(buf);
if (sec >= 10) newInterval = sec;
}
g_targetDir = target;
g_intervalSec = newInterval;
SaveConfig();
wprintf(L"\nSaved to %ls\nDisk: %ls\nCheck interval: %lu s\n",
g_iniPath.c_str(), g_targetDir.c_str(), g_intervalSec);
Sleep(1000);
return true;
}
// The core function: fxxk your disk
static void DoKeepAlive()
{
if (g_targetDir.empty()) return;
std::wstring dir = g_targetDir;
if (dir.back() != L'\\' && dir.back() != L'/') dir += L'\\';
const std::wstring tmpPath = dir + L"keepalive.tmp";
HANDLE h = CreateFileW(tmpPath.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr);
if (h != INVALID_HANDLE_VALUE)
{
const char data[] = "\n";
DWORD written = 0;
WriteFile(h, data, sizeof(data) - 1, &written, nullptr);
FlushFileBuffers(h);
CloseHandle(h);
DeleteFileW(tmpPath.c_str());
}
}
// Add a tray icon to taskbar
static void AddTrayIcon()
{
int traySize = GetSystemMetrics(SM_CXSMICON);
NOTIFYICONDATAW nid = {};
nid.cbSize = sizeof(nid);
nid.hWnd = g_hwnd;
nid.uID = TRAY_UID;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_TRAYICON;
nid.hIcon = (HICON)LoadImageW(
GetModuleHandleW(nullptr),
MAKEINTRESOURCEW(IDI_ICON1),
IMAGE_ICON,
traySize, traySize,
LR_DEFAULTCOLOR
);
wcscpy_s(nid.szTip, L"Disk KeepAlive");
Shell_NotifyIconW(NIM_ADD, &nid);
}
static void RemoveTrayIcon()
{
NOTIFYICONDATAW nid = {};
nid.cbSize = sizeof(nid);
nid.hWnd = g_hwnd;
nid.uID = TRAY_UID;
Shell_NotifyIconW(NIM_DELETE, &nid);
}
static void UpdateTrayTip()
{
NOTIFYICONDATAW nid = {};
nid.cbSize = sizeof(nid);
nid.hWnd = g_hwnd;
nid.uID = TRAY_UID;
nid.uFlags = NIF_TIP;
swprintf_s(nid.szTip, L"Disk KeepAlive - %ls\nStatus: %ls",
g_targetDir.empty() ? L"(none)" : g_targetDir.c_str(),
g_paused ? L"Paused" : L"Working");
Shell_NotifyIconW(NIM_MODIFY, &nid);
}
static void ShowTrayMenu()
{
POINT pt; GetCursorPos(&pt);
HMENU menu = CreatePopupMenu();
AppendMenuW(menu, MF_STRING, IDM_SHOW_STATUS, L"Show status");
AppendMenuW(menu, MF_STRING, IDM_RECONFIG, L"Reconfig...");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, IDM_TOGGLE_PAUSE, g_paused ? L"Rusume" : L"Pause");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, IDM_EXIT, L"Exit");
SetForegroundWindow(g_hwnd);
TrackPopupMenu(menu, TPM_RIGHTBUTTON | TPM_BOTTOMALIGN, pt.x, pt.y, 0, g_hwnd, nullptr);
DestroyMenu(menu);
}
static void ShowStatus()
{
wchar_t msg[512];
swprintf_s(msg, L"Disk: %ls\nInterval: %lu s\nStaus: %ls\nConfig: %ls",
g_targetDir.empty() ? L"(none)" : g_targetDir.c_str(),
g_intervalSec, g_paused ? L"Paused" : L"Working",
g_iniPath.c_str());
MessageBoxW(g_hwnd, msg, L"Keep Disk Alive", MB_OK | MB_ICONINFORMATION);
}
// Timer
static void StartKeepAliveTimer()
{
DoKeepAlive();
SetTimer(g_hwnd, TIMER_KEEPALIVE, g_intervalSec * 1000, nullptr);
}
static void StopKeepAliveTimer()
{
KillTimer(g_hwnd, TIMER_KEEPALIVE);
}
// Restore if reconfig
static void Reconfigure()
{
StopKeepAliveTimer();
if (AllocConsole())
{
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
freopen_s(&f, "CONOUT$", "w", stderr);
freopen_s(&f, "CONIN$", "r", stdin);
}
bool ok = AskUserForConfig(false);
if (ok)
{
g_paused = false;
StartKeepAliveTimer();
}
else
{
// if cancelled
StartKeepAliveTimer();
}
UpdateTrayTip();
if (HWND console = GetConsoleWindow())
{
FreeConsole();
PostMessageW(console, WM_SYSCOMMAND, SC_CLOSE, 0);
}
}
// Window
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
g_hwnd = hwnd;
AddTrayIcon();
UpdateTrayTip();
if (!g_targetDir.empty())
StartKeepAliveTimer();
return 0;
case WM_TIMER:
if (wParam == TIMER_KEEPALIVE && !g_paused) DoKeepAlive();
return 0;
case WM_TRAYICON:
switch (LOWORD(lParam))
{
case WM_RBUTTONUP:
case WM_CONTEXTMENU: ShowTrayMenu(); break;
case WM_LBUTTONDBLCLK: ShowStatus(); break;
}
return 0;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDM_TOGGLE_PAUSE:
g_paused = !g_paused;
if (g_paused) StopKeepAliveTimer(); else StartKeepAliveTimer();
UpdateTrayTip();
break;
case IDM_SHOW_STATUS: ShowStatus(); break;
case IDM_RECONFIG: Reconfigure(); break;
case IDM_EXIT: DestroyWindow(hwnd); break;
}
return 0;
case WM_DESTROY:
StopKeepAliveTimer();
RemoveTrayIcon();
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
// WinMain
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR, int)
{
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
bool hasArgs = (argc >= 2 && argv[1][0] != L'\0');
if (hasArgs)
{
g_targetDir = NormalizeTarget(argv[1]);
if (argc >= 3)
{
DWORD sec = (DWORD)_wtoi(argv[2]);
if (sec >= 10) g_intervalSec = sec;
}
}
if (argv) LocalFree(argv);
if (!hasArgs)
{
if (!LoadConfig())
{
if (!AskUserForConfig(true))
return 0;
}
}
// Single-Instance
HANDLE mutex = CreateMutexW(nullptr, TRUE, L"KeepDiskAliveTray_Mutex");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBoxW(nullptr, L"Keep Disk Alive is already running.", L"Oops.", MB_OK | MB_ICONINFORMATION);
return 0;
}
// Hide the window since there's nothing in it.
const wchar_t* cls = L"KeepDiskAliveTrayClass";
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIconW(nullptr, IDI_APPLICATION);
wc.lpszClassName = cls;
RegisterClassExW(&wc);
HWND hwnd = CreateWindowExW(0, cls, L"Keep Disk Alive", 0,
0, 0, 0, 0, nullptr, nullptr, hInstance, nullptr);
if (!hwnd) return 1;
if (HWND console = GetConsoleWindow())
ShowWindow(console, SW_HIDE);
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if (mutex) CloseHandle(mutex);
return 0;
}
// ConsoleMain (if you using console system
int wmain(int argc, wchar_t** argv)
{
HINSTANCE hInstance = GetModuleHandleW(nullptr);
bool hasArgs = (argc >= 2 && argv[1][0] != L'\0');
if (hasArgs)
{
g_targetDir = NormalizeTarget(argv[1]);
if (argc >= 3)
{
DWORD sec = (DWORD)_wtoi(argv[2]);
if (sec >= 10) g_intervalSec = sec;
}
}
if (!hasArgs)
{
if (!LoadConfig())
{
if (!AskUserForConfig(true))
{
wprintf(L"\nConfig undone, press Enter to exit...");
getwchar();
return 0;
}
}
}
HANDLE mutex = CreateMutexW(nullptr, TRUE, L"KeepDiskAliveTray_Mutex");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBoxW(nullptr, L"Keep Disk Alive is already running.", L"Oops.", MB_OK | MB_ICONINFORMATION);
return 0;
}
const wchar_t* cls = L"KeepDiskAliveTrayClass";
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hIcon = (HICON)LoadImageW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDI_ICON1), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
wc.hIconSm = (HICON)LoadImageW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDI_ICON1), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
wc.lpszClassName = cls;
RegisterClassExW(&wc);
HWND hwnd = CreateWindowExW(0, cls, L"Keep Disk Alive", 0,
0, 0, 0, 0, nullptr, nullptr, hInstance, nullptr);
if (!hwnd)
{
wprintf(L"Failed to create window, GetLastError=%lu\n", GetLastError());
getwchar();
return 1;
}
SetConsoleTitleW(L"Keep Disk Alive");
// Hide console
if (HWND console = GetConsoleWindow())
{
// This bullshit just minimizes your console, don't use it
// ShowWindow(console, SW_HIDE);
wprintf(L"You can close this console now.\nCheck your taskbar :D\n");
// Don't call wprintf() or printf() after FreeConsole().
// Unless you want to see a super mega beautiful crash.
FreeConsole();
// This bullshit is useless too if you are using Windows Terminal >:(
PostMessageW(console, WM_SYSCOMMAND, SC_CLOSE, 0);
}
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if (mutex) CloseHandle(mutex);
return 0;
}