-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmnotify.c
723 lines (612 loc) · 21.6 KB
/
mnotify.c
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
#define INITGUID
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#define SECURITY_WIN32
#include <security.h>
#include <schannel.h>
#include <shlwapi.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <intrin.h>
#include <shellapi.h>
#include <windowsx.h>
#include <strsafe.h>
#include <stdint.h>
#pragma comment (lib, "kernel32.lib")
#pragma comment (lib, "user32.lib")
#pragma comment (lib, "gdi32.lib")
#pragma comment (lib, "shell32.lib")
#pragma comment (lib, "ws2_32.lib")
#pragma comment (lib, "secur32.lib")
#pragma comment (lib, "shlwapi.lib")
#pragma comment (lib, "uxtheme.lib")
#pragma comment (lib, "winmm.lib")
#include "tls.c"
#include "mnotify.h"
#include "tokenizer.c"
#include "imap_parser.h"
#include "imap_client.h"
#define WM_MNOTIFY_ALREADY_RUNNING (WM_USER+1)
#define WM_MNOTIFY_EMAIL_MESSAGE (WM_USER+2)
#define WM_MNOTIFY_EMAIL_CLEAR (WM_USER+3)
#define WM_MNOTIFY_COMMAND (WM_USER+4)
#define WM_MNOTIFY_ERROR (WM_USER+5)
#define MNOTIFY_TIMER_RECOVER 1
#define CMD_MNOTIFY 1
#define CMD_QUIT 2
#define CMD_LOG 3
#define MNOTIFY_WINDOW_CLASS_NAME L"mnotify_window_class"
#define MNOTIFY_WINDOW_TITLE L"MNotify"
#define MNOTIFY_CONFIG_FILE "./mnotify.ini"
#define MNOTIFY_CONFIG_FILEW L"./mnotify.ini"
#define MNOTIFY_LOG_FILE "log.txt"
#define MNOTIFY_APPID L"MNotify.MNotify" // CompanyName.ProductName
#define MNOTIFY_LOGO_FILE_NAME L"mnotify_logo.png"
#define RESTART_IMAP_IDLE_TIMER_ID 1
#define RESTART_IMAP_IDLE_INTERVAL 25 * 1000 * 60 // 25 Minutes
#define HR(hr) do { HRESULT _hr = (hr); assert(SUCCEEDED(_hr)); } while (0)
#include "imap_parser.c"
#include "imap_client.c"
#include "WindowsToast.h"
// Globals
static UINT WM_TASKBARCREATED;
static HICON GlobalOpenIcon;
static HICON GlobalClosedIcon;
static HICON GlobalOpenWarningIcon;
static HICON GlobalClosedWarningIcon;
static HWND GlobalWindow;
static WindowsToast Toast;
static void* Notification;
// NOTE(Oskar): IDLE needs to reset every 29 minutes to prevent server from kicking
// us out so we store the currently used Imap Client globally so if the background thread
// is blocked reading messages the main thread can close the connection forcing a reset.
static imap GlobalImapIdleClient;
static BOOL GlobalImapIdleClientWasReset;
static mnotify_config GlobalConfiguration;
static BOOL GlobalHasErrors;
static unsigned int EmailCount;
static void
Win32FatalErrorMessage(char *Message)
{
MessageBox(NULL, Message, "Error", MB_OK);
ExitProcess(-1);
}
static void
Win32FatalErrorCode(LPSTR Message)
{
LPSTR ErrorMessage;
DWORD LastError = GetLastError();
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
LastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&ErrorMessage,
0, NULL );
int Characters = (lstrlen(ErrorMessage) + lstrlen(Message) + 40);
LPTSTR MessageBuffer = (LPTSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Characters * sizeof(CHAR));
StringCchPrintfA(MessageBuffer, Characters, "%s Error failed with error code %d: %s",
Message, LastError, ErrorMessage);
MessageBox(NULL, MessageBuffer, "Error", MB_OK);
LocalFree(ErrorMessage);
HeapFree(GetProcessHeap(), 0, MessageBuffer);
ExitProcess(LastError);
}
static BOOL
FileExists(char *FilePath)
{
return GetFileAttributesA(FilePath) != INVALID_FILE_ATTRIBUTES;
}
static void
CreateNewFile(char *FilePath)
{
HANDLE File = {0};
SECURITY_ATTRIBUTES SecurityAttributes =
{
.nLength = (DWORD)sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = 0,
.bInheritHandle = 0,
};
if ((File = CreateFile(FilePath,
GENERIC_READ | GENERIC_WRITE,
0,
&SecurityAttributes,
CREATE_ALWAYS,
0,
0)) != INVALID_HANDLE_VALUE)
{
CloseHandle(File);
}
else
{
Win32FatalErrorCode("Failed to create logfile.");
}
}
static void
AppendToFile(char *FilePath, void *Data, unsigned int DataLength)
{
HANDLE File = {0};
SECURITY_ATTRIBUTES SecurityAttributes =
{
.nLength = (DWORD)sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = 0,
.bInheritHandle = 0,
};
if ((File = CreateFile(FilePath,
FILE_APPEND_DATA,
0,
&SecurityAttributes,
OPEN_ALWAYS,
0,
0))
!= INVALID_HANDLE_VALUE)
{
void *WriteData = Data;
SetFilePointer(File, 0, 0, FILE_END);
DWORD NumberOfBytesWritten = 0;
WriteFile(File, WriteData, (DWORD)DataLength, &NumberOfBytesWritten, 0);
CloseHandle(File);
}
else
{
Win32FatalErrorCode("Failed to write to logfile.");
}
}
static void
ShowNotification(LPCWSTR Message, LPCWSTR Title, LPCWSTR OpenLink)
{
static WCHAR ImagePath[MAX_PATH];
WCHAR ExeFolder[MAX_PATH];
GetModuleFileNameW(NULL, ExeFolder, ARRAYSIZE(ExeFolder));
PathRemoveFileSpecW(ExeFolder);
wsprintfW(ImagePath, L"%s/%s", ExeFolder, MNOTIFY_LOGO_FILE_NAME);
for (WCHAR* P = ImagePath; *P; P++)
{
if (*P == '\\') *P = '/';
}
WCHAR Xml[2048];
int XmlLength = 0;
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"<toast duration=\"short\"><visual><binding template=\"ToastGeneric\">"
L"<image placement=\"appLogoOverride\" src=\"file:///");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, ImagePath);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"\"/>"
L"<text>{title}</text>"
L"<text>{message}</text>"
L"</binding></visual><actions>");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, L"<action content=\"Open\" arguments=\"");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, OpenLink);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"\"/>"
L"</actions></toast>");
LPCWSTR Data[][2] =
{
{ L"title", Title },
{ L"message", Message },
};
Notification = WindowsToast_Create(&Toast, Xml, XmlLength, Data, ARRAYSIZE(Data));
WindowsToast_Show(&Toast, Notification);
}
static void
AddTrayIcon(HWND Window)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP,
.uCallbackMessage = WM_MNOTIFY_COMMAND,
.hIcon = GlobalOpenIcon,
};
StrCpyNW(Data.szTip, MNOTIFY_WINDOW_TITLE, _countof(Data.szTip));
Shell_NotifyIconW(NIM_ADD, &Data);
}
static void
UpdateTrayIcon(HICON Icon)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = GlobalWindow,
.uFlags = NIF_ICON,
.hIcon = Icon,
};
Shell_NotifyIconW(NIM_MODIFY, &Data);
}
static void
RemoveTrayIcon(HWND Window)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
};
Shell_NotifyIconW(NIM_DELETE, &Data);
}
static void
ReadConfigurationFileString(char *Section, char *Key, char *Out, int OutLength)
{
GetPrivateProfileString(Section, Key, "", Out, OutLength, MNOTIFY_CONFIG_FILE);
if (strcmp(Out, "") == 0)
{
Win32FatalErrorCode("Reading Configuration failed, check your filename and values.");
}
}
static int
ReadConfigurationFileInt(char *Section, char *Key)
{
int Result = GetPrivateProfileInt(Section, Key, -1, MNOTIFY_CONFIG_FILE);
if (Result == -1)
{
Win32FatalErrorCode("Reading Configuration failed, check your filename and values.");
}
return Result;
}
static mnotify_config
LoadConfiguration()
{
mnotify_config Config = {0};
ReadConfigurationFileString("Account", "host", Config.Host, 256);
ReadConfigurationFileString("Account", "accountname", Config.Account, 256);
ReadConfigurationFileString("Account", "password", Config.Password, 256);
ReadConfigurationFileString("Account", "opensite", Config.OpenSite, 256);
ReadConfigurationFileString("Account", "folder", Config.Folder, 256);
Config.Port = ReadConfigurationFileInt("Account", "port");
Config.PollingTimeSeconds = ReadConfigurationFileInt("Account", "pollingtimer");
Config.RetryTime = ReadConfigurationFileInt("Account", "retrytime");
return Config;
}
static void
ImapPerformPolling(char *Host, int Port, char *Account, char *Password)
{
for (;;)
{
imap Imap;
if (imap_init(&Imap, Host, Port) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
return;
}
if(imap_login(&Imap, Account, Password) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
return;
}
if(imap_examine(&Imap, GlobalConfiguration.Folder) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
goto polling_sleep;
}
// NOTE(Oskar): We resort to polling
imap_search_response SearchResult = imap_search(&Imap);
if (SearchResult.Error != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
goto polling_sleep;
}
// NOTE(Oskar): Find out which emails we want to get
if (SearchResult.NumberOfMails != EmailCount)
{
// NOTE(Oskar): We only trigger a notification if stored number of
// unread emails are lower than what exists in mailbox.
if (EmailCount < SearchResult.NumberOfMails)
{
PostMessageW(GlobalWindow, WM_MNOTIFY_EMAIL_CLEAR, 0, 0);
PostMessageW(GlobalWindow, WM_MNOTIFY_EMAIL_MESSAGE, 0, (LPARAM)SearchResult.NumberOfMails);
}
else
{
EmailCount = SearchResult.NumberOfMails;
}
}
polling_sleep: ;
Sleep(GlobalConfiguration.PollingTimeSeconds * 1000);
}
}
void CALLBACK
ImapPerformIdleTimerCallback(HWND Hwnd, UINT uMsg, UINT_PTR TimerId, DWORD DwTime)
{
KillTimer(GlobalWindow, RESTART_IMAP_IDLE_TIMER_ID);
GlobalImapIdleClientWasReset = TRUE;
imap_destroy(&GlobalImapIdleClient);
}
static void
ImapPerformIdle(char *Host, int Port, char *Account, char *Password)
{
for (;;)
{
GlobalImapIdleClientWasReset = FALSE;
if (imap_init(&GlobalImapIdleClient, Host, Port) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)GlobalImapIdleClient.Error, (LPARAM)GlobalImapIdleClient.ErrorLength);
return;
}
if(imap_login(&GlobalImapIdleClient, Account, Password) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)GlobalImapIdleClient.Error, (LPARAM)GlobalImapIdleClient.ErrorLength);
return;
}
if(imap_examine(&GlobalImapIdleClient, GlobalConfiguration.Folder) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)GlobalImapIdleClient.Error, (LPARAM)GlobalImapIdleClient.ErrorLength);
return;
}
for (;;)
{
KillTimer(GlobalWindow, RESTART_IMAP_IDLE_TIMER_ID);
SetTimer(GlobalWindow, RESTART_IMAP_IDLE_TIMER_ID, RESTART_IMAP_IDLE_INTERVAL, ImapPerformIdleTimerCallback);
if(imap_idle(&GlobalImapIdleClient) != IMAP_CLIENT_ERROR_SUCCESS)
{
break;
}
imap_idle_response_type IdleResponseType = IMAP_IDLE_MESSAGE_UNKNOWN;
while (IdleResponseType != IMAP_IDLE_MESSAGE_EXISTS)
{
imap_idle_response IdleResponse = imap_idle_listen(&GlobalImapIdleClient);
if (IdleResponse.Error != IMAP_CLIENT_ERROR_SUCCESS)
{
break;
}
IdleResponseType = IdleResponse.Type;
if (IdleResponseType == IMAP_IDLE_MESSAGE_EXPUNGE)
{
if (EmailCount > 0)
{
--EmailCount;
}
}
}
if (imap_done(&GlobalImapIdleClient) != IMAP_CLIENT_ERROR_SUCCESS)
{
break;
}
imap_search_response SearchResult = imap_search(&GlobalImapIdleClient);
if (SearchResult.Error != IMAP_CLIENT_ERROR_SUCCESS)
{
break;
}
// NOTE(Oskar): Find out which emails we want to get
if (SearchResult.NumberOfMails != EmailCount)
{
PostMessageW(GlobalWindow, WM_MNOTIFY_EMAIL_CLEAR, 0, 0);
// TODO(Oskar): For later if we want to display the data somehow within the application.
// The parsing is broken through so need to fix that first. It dies on longer requests as we don't
// get the full imap message in one go from gmail and idk how to fix it.
// imap_response FetchResponse = imap_fetch(&Imap, SearchResult.SequenceNumbers, SearchResult.NumberOfNumbers);
// if (!FetchResponse.Success)
// {
// break;
// }
PostMessageW(GlobalWindow, WM_MNOTIFY_EMAIL_MESSAGE, 0, (LPARAM)SearchResult.NumberOfMails);
}
}
// NOTE(Oskar): Check if it was us who reset the connection
if (!GlobalImapIdleClientWasReset)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)GlobalImapIdleClient.Error, (LPARAM)GlobalImapIdleClient.ErrorLength);
imap_destroy(&GlobalImapIdleClient);
}
}
}
DWORD WINAPI
ImapBackgroundThread(LPVOID lpParameter)
{
// TODO(Oskar): How do we recover from init and login errors? Do we add
// option for user to restart the thread?
imap Imap;
if (imap_init(&Imap, GlobalConfiguration.Host, GlobalConfiguration.Port) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
goto thread_fatal;
}
if(imap_login(&Imap, GlobalConfiguration.Account, GlobalConfiguration.Password) != IMAP_CLIENT_ERROR_SUCCESS)
{
SendMessage(GlobalWindow, WM_MNOTIFY_ERROR, (WPARAM)Imap.Error, (LPARAM)Imap.ErrorLength);
goto thread_fatal;
}
imap_destroy(&Imap);
if (Imap.HasIdle)
{
ImapPerformIdle(GlobalConfiguration.Host, GlobalConfiguration.Port, GlobalConfiguration.Account, GlobalConfiguration.Password);
}
else
{
// NOTE(Oskar): No IDLE command support so we proceed with polling.
ImapPerformPolling(GlobalConfiguration.Host, GlobalConfiguration.Port, GlobalConfiguration.Account, GlobalConfiguration.Password);
}
thread_fatal: ;
SetTimer(GlobalWindow, MNOTIFY_TIMER_RECOVER, GlobalConfiguration.RetryTime * 1000, NULL);
return -1;
}
static LRESULT CALLBACK
WindowProc(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam)
{
if (Message == WM_CREATE)
{
HR(BufferedPaintInit());
AddTrayIcon(Window);
return 0;
}
else if (Message == WM_DESTROY)
{
RemoveTrayIcon(Window);
KillTimer(Window, RESTART_IMAP_IDLE_TIMER_ID);
PostQuitMessage(0);
return 0;
}
else if (Message == WM_TIMER)
{
if (WParam == MNOTIFY_TIMER_RECOVER)
{
KillTimer(Window, MNOTIFY_TIMER_RECOVER);
HANDLE Thread = CreateThread(0, 0, ImapBackgroundThread, 0, 0, NULL);
CloseHandle(Thread);
}
}
else if (Message == WM_MNOTIFY_EMAIL_MESSAGE)
{
int TotalEmails = (int)LParam;
EmailCount = TotalEmails;
if (EmailCount == 0)
{
GlobalHasErrors ? UpdateTrayIcon(GlobalOpenWarningIcon) : UpdateTrayIcon(GlobalOpenIcon);
}
else
{
GlobalHasErrors ? UpdateTrayIcon(GlobalClosedWarningIcon) : UpdateTrayIcon(GlobalClosedIcon);
wchar_t Data[512];
swprintf(Data, 512, L"You have %d unread mail.", EmailCount);
wchar_t Link[512];
swprintf(Link, 512, L"%hs", GlobalConfiguration.OpenSite);
if (Notification != NULL)
{
WindowsToast_Release(&Toast, Notification);
}
ShowNotification(Data, L"You've got new mails!", Link);
}
return 0;
}
else if (Message == WM_MNOTIFY_EMAIL_CLEAR)
{
EmailCount = 0;
}
else if (Message == WM_MNOTIFY_COMMAND)
{
if (LOWORD(LParam) == WM_RBUTTONUP)
{
HMENU Menu = CreatePopupMenu();
assert(Menu);
AppendMenuW(Menu, MF_STRING, CMD_MNOTIFY, MNOTIFY_WINDOW_TITLE);
AppendMenuW(Menu, MF_SEPARATOR, 0, NULL);
// TODO(Oskar): Future features?
if (GlobalHasErrors)
{
AppendMenuW(Menu, MF_STRING, CMD_LOG, L"Show Log");
}
AppendMenuW(Menu, MF_STRING, CMD_QUIT, L"Exit");
POINT Mouse;
GetCursorPos(&Mouse);
SetForegroundWindow(Window);
int Command = TrackPopupMenu(Menu, TPM_RETURNCMD | TPM_NONOTIFY, Mouse.x, Mouse.y, 0, Window, NULL);
if (Command == CMD_MNOTIFY)
{
ShellExecute(NULL, "open", GlobalConfiguration.OpenSite, NULL, NULL, SW_SHOWNORMAL);
}
else if (Command == CMD_QUIT)
{
DestroyWindow(Window);
}
else if (Command == CMD_LOG)
{
ShellExecute(NULL, "open", MNOTIFY_LOG_FILE, NULL, NULL, SW_SHOWNORMAL);
// NOTE(Oskar): User has viewed errors so we reset the icon back
GlobalHasErrors = FALSE;
if (EmailCount == 0)
{
UpdateTrayIcon(GlobalOpenIcon);
}
else
{
UpdateTrayIcon(GlobalClosedIcon);
}
}
DestroyMenu(Menu);
}
else if (LOWORD(LParam) == WM_LBUTTONDBLCLK)
{
}
return 0;
}
else if (Message == WM_MNOTIFY_ERROR)
{
GlobalHasErrors = TRUE;
char *Error = (char *)WParam;
int ErrorLength = (int)LParam;
AppendToFile(MNOTIFY_LOG_FILE, Error, ErrorLength);
if (EmailCount == 0)
{
UpdateTrayIcon(GlobalOpenWarningIcon);
}
else
{
UpdateTrayIcon(GlobalClosedWarningIcon);
}
return 0;
}
return DefWindowProcW(Window, Message, WParam, LParam);
}
static void MNotifyToastCallback(WindowsToast* Toast, void* Item, LPCWSTR Action)
{
LPCWSTR Url = Action;
ShellExecuteW(NULL, L"open", Url, NULL, NULL, SW_SHOWNORMAL);
}
int CALLBACK
WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode)
{
WNDCLASSEXW WindowClass =
{
.cbSize = sizeof(WindowClass),
.lpfnWndProc = WindowProc,
.hInstance = GetModuleHandleW(NULL),
.lpszClassName = L"mnotify_window_class",
};
// NOTE(Oskar): Check if running
HWND MNotifyWindow = FindWindowW(WindowClass.lpszClassName, NULL);
if (MNotifyWindow)
{
PostMessageW(MNotifyWindow, WM_MNOTIFY_ALREADY_RUNNING, 0, 0);
ExitProcess(0);
}
WindowsToast_Init(&Toast, MNOTIFY_WINDOW_TITLE, MNOTIFY_APPID);
WindowsToast_HideAll(&Toast, MNOTIFY_APPID);
Toast.OnActivatedCallback = MNotifyToastCallback;
WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated");
assert(WM_TASKBARCREATED);
GlobalOpenIcon = LoadIconW(WindowClass.hInstance, MAKEINTRESOURCEW(1));
GlobalClosedIcon = LoadIconW(WindowClass.hInstance, MAKEINTRESOURCEW(2));
GlobalOpenWarningIcon = LoadIconW(WindowClass.hInstance, MAKEINTRESOURCEW(3));
GlobalClosedWarningIcon = LoadIconW(WindowClass.hInstance, MAKEINTRESOURCEW(4));
assert(GlobalOpenIcon && GlobalClosedIcon && GlobalOpenWarningIcon && GlobalClosedWarningIcon);
// NOTE(Oskar): Load configuration
GlobalConfiguration = LoadConfiguration();
// NOTE(Oskar): Prepare Logfile
if (FileExists(MNOTIFY_LOG_FILE))
{
DeleteFileA(MNOTIFY_LOG_FILE);
}
CreateNewFile(MNOTIFY_LOG_FILE);
GlobalHasErrors = FALSE;
// NOTE(Oskar): Window Creation
ATOM Atom = RegisterClassExW(&WindowClass);
assert(Atom);
GlobalWindow = CreateWindowExW(
0, WindowClass.lpszClassName, MNOTIFY_WINDOW_TITLE, WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, WindowClass.hInstance, NULL);
if (!GlobalWindow)
{
ExitProcess(0);
}
// TODO(Oskar): Later create 1 per email account?
HANDLE Thread = CreateThread(0, 0, ImapBackgroundThread, 0, 0, NULL);
CloseHandle(Thread);
EmailCount = 0;
for (;;)
{
MSG Message;
BOOL Result = GetMessageW(&Message, NULL, 0, 0);
if (Result == 0)
{
ExitProcess(0);
}
assert(Result > 0);
TranslateMessage(&Message);
DispatchMessageW(&Message);
}
}