-
Notifications
You must be signed in to change notification settings - Fork 216
/
Notepad4.cpp
8586 lines (7581 loc) · 259 KB
/
Notepad4.cpp
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
/******************************************************************************
*
*
* Notepad4
*
* Notepad4.cpp
* Main application window functionality
*
* See Readme.txt for more information about this source code.
* Please send me your comments to this work.
*
* See License.txt for details about distribution and modification.
*
* (c) Florian Balmer 1996-2011
* florian.balmer@gmail.com
* https://www.flos-freeware.ch
*
*
******************************************************************************/
struct IUnknown;
#include <windows.h>
#include <windowsx.h>
#include <shlwapi.h>
#include <shlobj.h>
#include <shellapi.h>
#include <commctrl.h>
#include <commdlg.h>
#include <uxtheme.h>
#include <cstdio>
#include <cinttypes>
#include "SciCall.h"
#include "VectorISA.h"
#include "config.h"
#include "Helpers.h"
#include "Notepad4.h"
#include "Edit.h"
#include "Styles.h"
#include "Dialogs.h"
#include "resource.h"
#ifndef SM_CXPADDEDBORDER
#define SM_CXPADDEDBORDER 92
#endif
//! show code folding level and state on line number margin
#define NP2_DEBUG_CODE_FOLDING 0
/******************************************************************************
*
* Local and global Variables for Notepad4.cpp
*
*/
HWND hwndStatus;
static HWND hwndToolbar;
static HWND hwndReBar;
static HMONITOR hCurrentMonitor = nullptr;
HWND hwndEdit;
HWND hwndMain;
static HMENU hmenuMain;
static HWND hwndNextCBChain = nullptr;
HWND hDlgFindReplace = nullptr;
static bool bInitDone = false;
static HACCEL hAccMain;
static HACCEL hAccFindReplace;
static HICON hTrayIcon = nullptr;
static UINT uTrayIconDPI = 0;
// tab width for notification text
#define CallTipTabWidthNotification 8
#define CallTipDefaultMouseDwellTime 250
#define TOOLBAR_COMMAND_BASE IDT_FILE_NEW
#define DefaultToolbarButtons L"22 3 0 1 2 0 4 18 19 0 5 6 0 7 8 9 20 0 10 11 0 12 0 24 0 13 14 0 15 16 0 17"
static TBBUTTON tbbMainWnd[] = {
{0, 0, 0, TBSTYLE_SEP, {0}, 0, 0},
{0, IDT_FILE_NEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{1, IDT_FILE_OPEN, TBSTATE_ENABLED, BTNS_DROPDOWN, {0}, 0, 0},
{2, IDT_FILE_BROWSE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{3, IDT_FILE_SAVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{4, IDT_EDIT_UNDO, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{5, IDT_EDIT_REDO, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{6, IDT_EDIT_CUT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{7, IDT_EDIT_COPY, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{8, IDT_EDIT_PASTE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{9, IDT_EDIT_FIND, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{10, IDT_EDIT_REPLACE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{11, IDT_VIEW_WORDWRAP, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{12, IDT_VIEW_ZOOMIN, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{13, IDT_VIEW_ZOOMOUT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{14, IDT_VIEW_SCHEME, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{15, IDT_VIEW_SCHEMECONFIG, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{16, IDT_FILE_EXIT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{17, IDT_FILE_SAVEAS, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{18, IDT_FILE_SAVECOPY, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{19, IDT_EDIT_DELETE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{20, IDT_FILE_PRINT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{21, IDT_FILE_OPENFAV, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{22, IDT_FILE_ADDTOFAV, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{23, IDT_VIEW_TOGGLEFOLDS, TBSTATE_ENABLED, BTNS_DROPDOWN, {0}, 0, 0},
{24, IDT_FILE_LAUNCH, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
{25, IDT_VIEW_ALWAYSONTOP, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, 0},
};
WCHAR szIniFile[MAX_PATH] = L"";
static WCHAR szIniFile2[MAX_PATH] = L"";
static bool bSaveSettings;
bool bSaveRecentFiles;
static bool bSaveFindReplace;
static WCHAR tchLastSaveCopyDir[MAX_PATH] = L"";
WCHAR tchOpenWithDir[MAX_PATH];
WCHAR tchFavoritesDir[MAX_PATH];
static WCHAR tchDefaultDir[MAX_PATH];
static WCHAR tchToolbarButtons[MAX_TOOLBAR_BUTTON_CONFIG_BUFFER_SIZE];
static LPWSTR tchToolbarBitmap = nullptr;
static LPWSTR tchToolbarBitmapHot = nullptr;
static LPWSTR tchToolbarBitmapDisabled = nullptr;
static TitlePathNameFormat iPathNameFormat;
bool fWordWrapG;
int iWordWrapMode;
int iWordWrapIndent;
int iWordWrapSymbols;
bool bShowWordWrapSymbols;
bool bWordWrapSelectSubLine;
static bool bShowUnicodeControlCharacter;
static bool bMatchBraces;
static bool bShowIndentGuides;
static bool bHighlightCurrentBlock;
bool bHighlightCurrentSubLine;
LineHighlightMode iHighlightCurrentLine;
EditTabSettings tabSettings;
static bool bMarkLongLines;
int iLongLinesLimitG;
int iLongLineMode;
int iWrapColumn = 0;
int iZoomLevel = 100;
bool bShowBookmarkMargin;
static bool bShowLineNumbers;
static int bMarkOccurrences;
EditAutoCompletionConfig autoCompletionConfig;
int iSelectOption;
static int iLineSelectionMode;
static bool bShowCodeFolding;
extern CallTipInfo callTipInfo;
static bool bViewWhiteSpace;
static bool bViewEOLs;
// DBCS code page
int iDefaultCodePage;
int iDefaultCharSet;
int iDefaultEncoding;
int iCurrentEncoding;
static int iOriginalEncoding;
int iSrcEncoding = CPI_NONE;
int iWeakSrcEncoding = CPI_NONE;
bool bSkipUnicodeDetection;
bool bLoadANSIasUTF8;
bool bLoadASCIIasUTF8;
bool bLoadNFOasOEM;
bool bNoEncodingTags;
extern int g_DOSEncoding;
#if defined(_WIN64)
bool bLargeFileMode = false;
#endif
int iDefaultEOLMode;
static int iCurrentEOLMode;
bool bWarnLineEndings;
bool bFixLineEndings;
bool bAutoStripBlanks;
PrintHeaderOption iPrintHeader;
PrintFooterOption iPrintFooter;
int iPrintColor;
int iPrintZoom = 100;
RECT pageSetupMargin;
static bool bSaveBeforeRunningTools;
bool bOpenFolderWithMatepath;
FileWatchingMode iFileWatchingMode;
bool iFileWatchingMethod;
bool bFileWatchingKeepAtEnd;
bool bResetFileWatching;
static DWORD dwFileCheckInterval;
static DWORD dwAutoReloadTimeout;
bool bUseXPFileDialog;
static EscFunction iEscFunction;
static bool bAlwaysOnTop;
static bool bMinimizeToTray;
static bool bTransparentMode;
static int iEndAtLastLine;
int iFindReplaceOption;
static bool bEditLayoutRTL;
bool bWindowLayoutRTL;
static int iRenderingTechnology;
static bool bUseInlineIME;
static int iBidirectional;
static bool bShowMenu;
static bool bShowToolbar;
static bool bAutoScaleToolbar;
static bool bShowStatusbar;
static bool bInFullScreenMode;
static int iFullScreenMode;
struct WININFO {
int x;
int y;
int cx;
int cy;
BOOL max;
};
static WININFO wi;
static int cyReBar;
static int cyReBarFrame;
int cxRunDlg;
int cxEncodingDlg;
int cyEncodingDlg;
int cxFileMRUDlg;
int cyFileMRUDlg;
int cxOpenWithDlg;
int cyOpenWithDlg;
int cxFavoritesDlg;
int cyFavoritesDlg;
int cxAddFavoritesDlg;
int cxModifyLinesDlg;
int cyModifyLinesDlg;
int cxEncloseSelectionDlg;
int cyEncloseSelectionDlg;
int cxInsertTagDlg;
int cyInsertTagDlg;
int xFindReplaceDlg;
int yFindReplaceDlg;
int cxFindReplaceDlg;
extern int cxStyleSelectDlg;
extern int cyStyleSelectDlg;
extern int cxStyleCustomizeDlg;
extern int cyStyleCustomizeDlg;
static LPWSTR lpFileList[32];
static int cFileList = 0;
static int cchiFileList = 0;
static LPWSTR lpFileArg = nullptr;
static LPWSTR lpSchemeArg = nullptr;
static LPWSTR lpMatchArg = nullptr;
static LPWSTR lpEncodingArg = nullptr;
MRUList mruFile;
MRUList mruFind;
MRUList mruReplace;
static BitmapCache bitmapCache;
DWORD dwLastIOError;
WCHAR szCurFile[MAX_PATH + 40];
EditFileVars fvCurFile;
static bool bDocumentModified = false;
static bool bReadOnlyFile = false;
bool bReadOnlyMode = false; // save call to SciCall_GetReadOnly()
// AutoSave
int iAutoSaveOption;
DWORD dwAutoSavePeriod;
static DWORD dwCurrentDocReversion = 0;
static DWORD dwLastSavedDocReversion = 0;
static bool bAutoSaveTimerSet = false;
#define MaxAutoSaveCount 6 // normal
#define AllAutoSaveCount (MaxAutoSaveCount + 2) // suspend, shutdown
static LPWSTR autoSavePathList[AllAutoSaveCount];
static int autoSaveCount = 0;
static WCHAR szAutoSaveFolder[MAX_PATH];
static Sci_Line iInitialLine;
static Sci_Position iInitialColumn;
static int iInitialLexer;
static bool bLastCopyFromMe = false;
static DWORD dwLastCopyTime;
bool bFreezeAppTitle = false;
static WCHAR szTitleExcerpt[128] = L"";
static bool fKeepTitleExcerpt = false;
static HANDLE hChangeHandle = nullptr;
static bool bRunningWatch = false;
static DWORD dwChangeNotifyTime = 0;
static UINT msgTaskbarCreated = 0;
static struct WatchFileInformation {
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
} fdCurFile;
static EDITFINDREPLACE efrData;
bool bReplaceInitialized = false;
EditMarkAll editMarkAll;
HANDLE idleTaskTimer;
static EditSortFlag iSortOptions = EditSortFlag_Ascending;
static EditAlignMode iAlignMode = EditAlignMode_Left;
extern int iFontQuality;
extern CaretStyle iCaretStyle;
extern bool bBlockCaretForOVRMode;
extern bool bBlockCaretOutSelection;
extern int iCaretBlinkPeriod;
bool fIsElevated = false;
static WCHAR wchWndClass[16] = WC_NOTEPAD4;
// rarely changed statusbar items
struct CachedStatusItem {
UINT updateMask;
BOOL overType;
Sci_Line iLine;
Sci_Position iLineChar;
Sci_Position iLineColumn;
LPCWSTR pszLexerName;
LPCWSTR pszEncoding;
LPCWSTR pszEolMode;
LPCWSTR pszOvrMode;
WCHAR tchZoom[8];
WCHAR tchItemFormat[128]; // IDS_STATUSITEM_FORMAT
WCHAR tchLexerName[MAX_EDITLEXER_NAME_SIZE];
};
static CachedStatusItem cachedStatusItem;
#define UpdateStatusBarCacheLineColumn() cachedStatusItem.updateMask |= (((1 << StatusItem_Find) - 1) | (1 << StatusItem_DocSize))
#define DisableDelayedStatusBarRedraw() cachedStatusItem.updateMask |= (1 << StatusItem_ItemCount)
HINSTANCE g_hInstance;
#if NP2_ENABLE_APP_LOCALIZATION_DLL
HINSTANCE g_exeInstance;
#endif
HANDLE g_hDefaultHeap;
HANDLE g_hScintilla;
#if _WIN32_WINNT < _WIN32_WINNT_WIN8
DWORD g_uWinVer;
#endif
#if _WIN32_WINNT < _WIN32_WINNT_WIN8
DWORD kSystemLibraryLoadFlags = 0;
#endif
UINT g_uCurrentDPI = USER_DEFAULT_SCREEN_DPI;
UINT g_uSystemDPI = USER_DEFAULT_SCREEN_DPI;
WCHAR g_wchAppUserModelID[64] = L"";
static WCHAR g_wchWorkingDirectory[MAX_PATH] = L"";
#if NP2_ENABLE_APP_LOCALIZATION_DLL
static HMODULE hResDLL;
LANGID uiLanguage;
static UINT languageMenu;
#endif
//=============================================================================
//
// Flags
//
enum {
DefaultPositionFlag_None = 0,
DefaultPositionFlag_SystemDefault = 1,
DefaultPositionFlag_DefaultLeft = 2,
DefaultPositionFlag_DefaultRight = 3,
DefaultPositionFlag_Custom = 4,
DefaultPositionFlag_AlignLeft = 4,
DefaultPositionFlag_AlignRight = 8,
DefaultPositionFlag_AlignTop = 16,
DefaultPositionFlag_AlignBottom = 32,
DefaultPositionFlag_FullArea = 64,
DefaultPositionFlag_Margin = 128,
};
enum NotepadReplacementAction {
NotepadReplacementAction_None,
NotepadReplacementAction_Default,
NotepadReplacementAction_PrintDialog,
NotepadReplacementAction_PrintDefault,
};
enum RelaunchElevatedFlag {
RelaunchElevatedFlag_None = 0,
RelaunchElevatedFlag_Startup,
RelaunchElevatedFlag_Manual,
};
static NotepadReplacementAction notepadAction = NotepadReplacementAction_None;
static bool flagNoReuseWindow = false;
static bool flagReuseWindow = false;
static bool bSingleFileInstance = true;
static bool bReuseWindow = false;
static bool bStickyWindowPosition = false;
static int flagReadOnlyMode = ReadOnlyMode_None;
static TripleBoolean flagMultiFileArg = TripleBoolean_NotSet;
static bool flagSingleFileInstance = true;
static bool flagStartAsTrayIcon = false;
static TripleBoolean flagAlwaysOnTop= TripleBoolean_NotSet;
static bool flagRelativeFileMRU = false;
static bool flagPortableMyDocs = false;
bool flagNoFadeHidden = false;
static int iOpacityLevel = 75;
int iFindReplaceOpacityLevel= 75;
bool flagSimpleIndentGuides = false;
bool fNoHTMLGuess = false;
bool fNoCGIGuess = false;
bool fNoAutoDetection = false;
bool fNoFileVariables = false;
static bool flagPosParam = false;
static int flagDefaultPos = DefaultPositionFlag_None;
static bool flagNewFromClipboard = false;
static bool flagPasteBoard = false;
static int flagSetEncoding = 0;
static int flagSetEOLMode = 0;
static bool flagJumpTo = false;
static MatchTextFlag flagMatchText = MatchTextFlag_None;
static TripleBoolean flagChangeNotify = TripleBoolean_NotSet;
static bool flagLexerSpecified = false;
static bool flagQuietCreate = false;
TripleBoolean flagUseSystemMRU = TripleBoolean_NotSet;
static RelaunchElevatedFlag flagRelaunchElevated = RelaunchElevatedFlag_None;
static bool flagDisplayHelp = false;
static inline bool IsDocumentModified() noexcept {
return bDocumentModified || iCurrentEncoding != iOriginalEncoding;
}
static inline bool IsTopMost() noexcept {
return (bAlwaysOnTop || flagAlwaysOnTop == TripleBoolean_True) && flagAlwaysOnTop != TripleBoolean_False;
}
// temporary fix for https://github.com/zufuliu/notepad4/issues/77: force InvalidateStyleRedraw().
static inline void InvalidateStyleRedraw() noexcept {
SciCall_SetViewEOL(bViewEOLs);
}
// temporary fix for https://github.com/zufuliu/notepad4/issues/134: Direct2D on arm32
static inline int GetDefualtRenderingTechnology() noexcept {
#if defined(__arm__) || defined(_ARM_) || defined(_M_ARM)
return SC_TECHNOLOGY_DIRECTWRITERETAIN;
#else
return IsVistaAndAbove()? SC_TECHNOLOGY_DIRECTWRITE : SC_TECHNOLOGY_DEFAULT;
#endif
}
//=============================================================================
//
// WinMain()
//
//
static void CleanUpResources(bool initialized) noexcept {
if (tchToolbarBitmap != nullptr) {
LocalFree(tchToolbarBitmap);
}
if (tchToolbarBitmapHot != nullptr) {
LocalFree(tchToolbarBitmapHot);
}
if (tchToolbarBitmapDisabled != nullptr) {
LocalFree(tchToolbarBitmapDisabled);
}
if (lpSchemeArg) {
LocalFree(lpSchemeArg);
}
Encoding_ReleaseResources();
Style_ReleaseResources();
Edit_ReleaseResources();
Scintilla_ReleaseResources();
if (hTrayIcon) {
DestroyIcon(hTrayIcon);
}
if (initialized) {
UnregisterClass(wchWndClass, g_hInstance);
}
#if NP2_ENABLE_APP_LOCALIZATION_DLL
if (hResDLL) {
FreeLibrary(hResDLL);
}
#endif
OleUninitialize();
}
static void DispatchMessageMain(MSG *msg) noexcept {
if (IsWindow(hDlgFindReplace) && (msg->hwnd == hDlgFindReplace || IsChild(hDlgFindReplace, msg->hwnd))) {
if (TranslateAccelerator(hDlgFindReplace, hAccFindReplace, msg) || IsDialogMessage(hDlgFindReplace, msg)) {
return;
}
}
if (!TranslateAccelerator(hwndMain, hAccMain, msg)) {
TranslateMessage(msg);
DispatchMessage(msg);
}
}
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType) noexcept {
if (dwCtrlType == CTRL_C_EVENT) {
SendWMCommand(hwndMain, IDM_FILE_EXIT);
return TRUE;
}
return FALSE;
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
#if 0 // used for Clang UBSan or printing debug message on console.
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
fprintf(stdout, "\n%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
}
#endif
#if 0 && defined(__clang__)
SetEnvironmentVariable(L"UBSAN_OPTIONS", L"log_path=" WC_NOTEPAD4 L"-UBSan.log");
#endif
// Set global variable g_hInstance
g_hInstance = hInstance;
#if NP2_ENABLE_APP_LOCALIZATION_DLL
g_exeInstance = hInstance;
#endif
#if _WIN32_WINNT < _WIN32_WINNT_WIN8
// Set the Windows version global variable
NP2_COMPILER_WARNING_PUSH
NP2_IGNORE_WARNING_DEPRECATED_DECLARATIONS
g_uWinVer = LOWORD(GetVersion());
NP2_COMPILER_WARNING_POP
g_uWinVer = MAKEWORD(HIBYTE(g_uWinVer), LOBYTE(g_uWinVer));
#endif
g_hDefaultHeap = GetProcessHeap();
// https://docs.microsoft.com/en-us/windows/desktop/Memory/low-fragmentation-heap
#if 0 // default enabled since Vista
{
// Enable the low-fragmenation heap (LFH).
ULONG HeapInformation = /*HEAP_LFH*/2;
HeapSetInformation(g_hDefaultHeap, HeapCompatibilityInformation, &HeapInformation, sizeof(HeapInformation));
// Enable heap terminate-on-corruption.
HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
}
#endif
// Don't keep working directory locked
WCHAR wchWorkingDirectory[MAX_PATH];
GetCurrentDirectory(COUNTOF(g_wchWorkingDirectory), g_wchWorkingDirectory);
GetModuleFileName(nullptr, wchWorkingDirectory, COUNTOF(wchWorkingDirectory));
PathRemoveFileSpec(wchWorkingDirectory);
SetCurrentDirectory(wchWorkingDirectory);
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
// Check if running with elevated privileges
fIsElevated = IsElevated();
// Default Encodings (may already be used for command line parsing)
Encoding_InitDefaults();
// Command Line, Ini File and Flags
ParseCommandLine();
FindIniFile();
TestIniFile();
CreateIniFile(szIniFile);
LoadFlags();
// set AppUserModelID
PrivateSetCurrentProcessExplicitAppUserModelID(g_wchAppUserModelID);
// Command Line Help Dialog
if (flagDisplayHelp) {
#if NP2_ENABLE_APP_LOCALIZATION_DLL
hResDLL = LoadLocalizedResourceDLL(uiLanguage, WC_NOTEPAD4 L".dll");
if (hResDLL) {
g_hInstance = hResDLL;
}
#endif
DisplayCmdLineHelp(nullptr);
#if NP2_ENABLE_APP_LOCALIZATION_DLL
if (hResDLL) {
FreeLibrary(hResDLL);
}
#endif
return 0;
}
// Adapt window class name
if (fIsElevated) {
lstrcat(wchWndClass, L"U");
}
if (flagPasteBoard) {
lstrcat(wchWndClass, L"B");
}
// Relaunch with elevated privileges
if (RelaunchElevated()) {
return 0;
}
// Try to run multiple instances
if (RelaunchMultiInst()) {
return 0;
}
// Try to activate another window
if (ActivatePrevInst()) {
NP2HeapFree(lpFileArg);
return 0;
}
// Init OLE and Common Controls
OleInitialize(nullptr);
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_WIN95_CLASSES | ICC_COOL_CLASSES | ICC_BAR_CLASSES | ICC_USEREX_CLASSES;
InitCommonControlsEx(&icex);
msgTaskbarCreated = RegisterWindowMessage(L"TaskbarCreated");
#if _WIN32_WINNT < _WIN32_WINNT_WIN8
// see LoadD2D() in PlatWin.cxx
kSystemLibraryLoadFlags = (DLLFunctionEx<FARPROC>(L"kernel32.dll", "SetDefaultDllDirectories") != nullptr) ? LOAD_LIBRARY_SEARCH_SYSTEM32 : 0;
#endif
#if NP2_ENABLE_APP_LOCALIZATION_DLL
hResDLL = LoadLocalizedResourceDLL(uiLanguage, WC_NOTEPAD4 L".dll");
if (hResDLL) {
g_hInstance = hInstance = hResDLL;
}
#endif
// we need DPI-related functions before create Scintilla window.
#if NP2_HAS_GETDPIFORWINDOW
g_uSystemDPI = GetDpiForSystem();
#else
Scintilla_LoadDpiForWindow();
#endif
Scintilla_RegisterClasses(hInstance);
// Load Settings
LoadSettings();
if (!InitApplication(hInstance)) {
CleanUpResources(false);
return FALSE;
}
// create the timer first, to make flagMatchText working.
HANDLE timer = idleTaskTimer = WaitableTimer_Create();
QueryPerformanceFrequency(&editMarkAll.watch.freq);
InitInstance(hInstance, nShowCmd);
hAccMain = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_MAINWND));
hAccFindReplace = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCFINDREPLACE));
MSG msg;
while (true) {
if (editMarkAll.pending) {
WaitableTimer_Set(timer, WaitableTimer_IdleTaskDelayTime);
while (editMarkAll.pending && WaitableTimer_Continue(timer)) {
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
DispatchMessageMain(&msg);
}
}
if (editMarkAll.pending) {
editMarkAll.Continue(timer);
}
}
if (GetMessage(&msg, nullptr, 0, 0)) {
DispatchMessageMain(&msg);
} else {
break;
}
}
WaitableTimer_Destroy(timer);
CleanUpResources(true);
return static_cast<int>(msg.wParam);
}
//=============================================================================
//
// InitApplication()
//
//
BOOL InitApplication(HINSTANCE hInstance) noexcept {
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_BYTEALIGNWINDOW | CS_DBLCLKS;
wc.lpfnWndProc = MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDR_MAINWND));
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = AsPointer<HBRUSH, ULONG_PTR>(COLOR_3DFACE + 1);
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MAINWND);
wc.lpszClassName = wchWndClass;
wc.hIconSm = nullptr;
return RegisterClassEx(&wc);
}
static void HandleMatchText(MatchTextFlag flag, LPCWSTR lpszText, bool jumpTo) noexcept {
if (StrNotEmpty(lpszText) && SciCall_GetLength()) {
const UINT cpEdit = SciCall_GetCodePage();
WideCharToMultiByte(cpEdit, 0, lpszText, -1, efrData.szFind, COUNTOF(efrData.szFind), nullptr, nullptr);
WideCharToMultiByte(CP_UTF8, 0, lpszText, -1, efrData.szFindUTF8, COUNTOF(efrData.szFindUTF8), nullptr, nullptr);
if (flag & MatchTextFlag_Regex) {
efrData.fuFlags |= (iFindReplaceOption & FindReplaceOption_UseCxxRegex) ? (SCFIND_REGEXP | SCFIND_CXX11REGEX) : (SCFIND_REGEXP | SCFIND_POSIX);
} else if (flag & MatchTextFlag_TransformBS) {
efrData.option |= FindReplaceOption_TransformBackslash;
}
if (flag & MatchTextFlag_FindUp) {
if (!jumpTo) {
SciCall_DocumentEnd();
}
EditFindPrev(&efrData, false);
} else {
if (!jumpTo) {
SciCall_DocumentStart();
}
EditFindNext(&efrData, false);
}
EditEnsureSelectionVisible();
}
}
//=============================================================================
//
// InitInstance()
//
//
void InitInstance(HINSTANCE hInstance, int nCmdShow) {
#if 0
StopWatch watch;
watch.Start();
#endif
const bool defaultPos = (wi.x == CW_USEDEFAULT || wi.y == CW_USEDEFAULT || wi.cx == CW_USEDEFAULT || wi.cy == CW_USEDEFAULT);
RECT rc = { wi.x, wi.y, (defaultPos ? CW_USEDEFAULT : (wi.x + wi.cx)), (defaultPos ? CW_USEDEFAULT : (wi.y + wi.cy)) };
if (flagDefaultPos == DefaultPositionFlag_SystemDefault) {
wi.x = wi.y = wi.cx = wi.cy = CW_USEDEFAULT;
wi.max = 0;
} else if (flagDefaultPos >= DefaultPositionFlag_Custom) {
SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
const int width = rc.right - rc.left;
const int height = rc.bottom - rc.top;
if (flagDefaultPos & DefaultPositionFlag_AlignRight) {
wi.x = width / 2;
} else {
wi.x = rc.left;
}
wi.cx = width;
if (flagDefaultPos & (DefaultPositionFlag_AlignLeft | DefaultPositionFlag_AlignRight)) {
wi.cx = width / 2;
}
if (flagDefaultPos & DefaultPositionFlag_AlignBottom) {
wi.y = height / 2;
} else {
wi.y = rc.top;
}
wi.cy = height;
if (flagDefaultPos & (DefaultPositionFlag_AlignTop | DefaultPositionFlag_AlignBottom)) {
wi.cy = height / 2;
}
if (flagDefaultPos & DefaultPositionFlag_FullArea) {
wi.x = rc.left;
wi.y = rc.top;
wi.cx = width;
wi.cy = height;
}
if (flagDefaultPos & DefaultPositionFlag_Margin) {
wi.x += (flagDefaultPos & DefaultPositionFlag_AlignRight) ? 4 : 8;
wi.cx -= (flagDefaultPos & (DefaultPositionFlag_AlignLeft | DefaultPositionFlag_AlignRight)) ? 12 : 16;
wi.y += (flagDefaultPos & DefaultPositionFlag_AlignBottom) ? 4 : 8;
wi.cy -= (flagDefaultPos & (DefaultPositionFlag_AlignTop | DefaultPositionFlag_AlignBottom)) ? 12 : 16;
}
} else if (flagDefaultPos == DefaultPositionFlag_DefaultLeft || flagDefaultPos == DefaultPositionFlag_DefaultRight || defaultPos) {
// default window position
SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
wi.y = rc.top + 16;
wi.cy = rc.bottom - rc.top - 32;
wi.cx = min<int>(rc.right - rc.left - 32, wi.cy);
wi.x = (flagDefaultPos == DefaultPositionFlag_DefaultLeft) ? rc.left + 16 : rc.right - wi.cx - 16;
} else {
// fit window into working area of current monitor
HMONITOR hMonitor = MonitorFromRect(&rc, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi;
mi.cbSize = sizeof(mi);
GetMonitorInfo(hMonitor, &mi);
wi.x += (mi.rcWork.left - mi.rcMonitor.left);
wi.y += (mi.rcWork.top - mi.rcMonitor.top);
if (wi.x < mi.rcWork.left) {
wi.x = mi.rcWork.left;
}
if (wi.y < mi.rcWork.top) {
wi.y = mi.rcWork.top;
}
if (wi.x + wi.cx > mi.rcWork.right) {
wi.x -= (wi.x + wi.cx - mi.rcWork.right);
if (wi.x < mi.rcWork.left) {
wi.x = mi.rcWork.left;
}
if (wi.x + wi.cx > mi.rcWork.right) {
wi.cx = mi.rcWork.right - wi.x;
}
}
if (wi.y + wi.cy > mi.rcWork.bottom) {
wi.y -= (wi.y + wi.cy - mi.rcWork.bottom);
if (wi.y < mi.rcWork.top) {
wi.y = mi.rcWork.top;
}
if (wi.y + wi.cy > mi.rcWork.bottom) {
wi.cy = mi.rcWork.bottom - wi.y;
}
}
SetRect(&rc, wi.x, wi.y, wi.x + wi.cx, wi.y + wi.cy);
RECT rc2;
if (!IntersectRect(&rc2, &rc, &mi.rcWork)) {
wi.y = mi.rcWork.top + 16;
wi.cy = mi.rcWork.bottom - mi.rcWork.top - 32;
wi.cx = min<int>(mi.rcWork.right - mi.rcWork.left - 32, wi.cy);
wi.x = mi.rcWork.right - wi.cx - 16;
}
}
HWND hwnd = CreateWindowEx(
0,
wchWndClass,
WC_NOTEPAD4,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
wi.x,
wi.y,
wi.cx,
wi.cy,
nullptr,
nullptr,
hInstance,
nullptr);
if (IsTopMost()) {
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
if (bTransparentMode) {
SetWindowTransparentMode(hwnd, true, iOpacityLevel);
}
if (!bShowMenu) {
SetMenu(hwnd, nullptr);
}
if (!flagStartAsTrayIcon) {
ShowWindow(hwnd, wi.max ? SW_SHOWMAXIMIZED : nCmdShow);
UpdateWindow(hwnd);
} else {
ShowWindow(hwnd, SW_HIDE); // trick ShowWindow()
ShowNotifyIcon(hwnd, true);
}
// Source Encoding
if (lpEncodingArg) {
iSrcEncoding = Encoding_Match(lpEncodingArg);
}
UpdateStatusBarCache(StatusItem_OvrMode);
UpdateStatusBarCache(StatusItem_Zoom);
bool bOpened = false;
bool bFileLoadCalled = false;
// Pathname parameter
if (lpFileArg /*&& !flagNewFromClipboard*/) {
// Open from Directory
if (PathIsDirectory(lpFileArg)) {
WCHAR tchFile[MAX_PATH];
if (OpenFileDlg(tchFile, COUNTOF(tchFile), lpFileArg)) {
bOpened = FileLoad(FileLoadFlag_Default, tchFile);
bFileLoadCalled = true;
}
} else {
bOpened = FileLoad(FileLoadFlag_Default, lpFileArg);
bFileLoadCalled = bOpened;
}
NP2HeapFree(lpFileArg);
if (bOpened) {
if (flagJumpTo) { // Jump to position
EditJumpTo(iInitialLine, iInitialColumn);
}
if (flagChangeNotify != TripleBoolean_NotSet) {
iFileWatchingMode = (flagChangeNotify == TripleBoolean_False) ? FileWatchingMode_None : FileWatchingMode_AutoReload;
bResetFileWatching = true;
InstallFileWatching(false);
}
}
} else {
if (iSrcEncoding >= CPI_FIRST) {
iCurrentEncoding = iSrcEncoding;
iOriginalEncoding = iSrcEncoding;
SciCall_SetCodePage((iSrcEncoding == CPI_DEFAULT) ? iDefaultCodePage : SC_CP_UTF8);
}
}
if (!bFileLoadCalled) {
bOpened = FileLoad(static_cast<FileLoadFlag>(FileLoadFlag_DontSave | FileLoadFlag_New), L"");
}
if (!bOpened) {
UpdateStatusBarCache(StatusItem_Encoding);
UpdateStatusBarCache(StatusItem_EolMode);
UpdateStatusBarCacheLineColumn();
}
// reset
iSrcEncoding = CPI_NONE;
flagQuietCreate = false;
fKeepTitleExcerpt = false;
// Check for /c [if no file is specified] -- even if a file is specified
if (flagNewFromClipboard) {
if (SciCall_CanPaste()) {
const bool back = autoCompletionConfig.bIndentText;
autoCompletionConfig.bIndentText = false;
SciCall_DocumentEnd();
SciCall_BeginUndoAction();
if (SciCall_GetLength() > 0) {
SciCall_NewLine();
}
SciCall_Paste(false);
SciCall_NewLine();
SciCall_EndUndoAction();
autoCompletionConfig.bIndentText = back;
if (flagJumpTo) {
EditJumpTo(iInitialLine, iInitialColumn);
} else {
EditEnsureSelectionVisible();
}
}
}
// Encoding
if (0 != flagSetEncoding) {
SendWMCommand(hwnd, IDM_ENCODING_ANSI - 1 + flagSetEncoding);
flagSetEncoding = 0;
}
// EOL mode
if (0 != flagSetEOLMode) {
SendWMCommand(hwnd, IDM_LINEENDINGS_CRLF - 1 + flagSetEOLMode);
flagSetEOLMode = 0;
}
// Match Text
if (lpMatchArg) {
HandleMatchText(flagMatchText, lpMatchArg, flagJumpTo);
LocalFree(lpMatchArg);
}
// Check for Paste Board option -- after loading files
if (flagPasteBoard) {
bLastCopyFromMe = true;
hwndNextCBChain = SetClipboardViewer(hwnd);
UpdateWindowTitle();
bLastCopyFromMe = false;
dwLastCopyTime = 0;
SetTimer(hwnd, ID_PASTEBOARDTIMER, 100, PasteBoardTimer);
}
// check if a lexer was specified from the command line
if (flagLexerSpecified) {
if (lpSchemeArg) {
Style_SetLexerFromName(szCurFile, lpSchemeArg);
LocalFree(lpSchemeArg);
lpSchemeArg = nullptr;
} else {
Style_SetLexerFromID(iInitialLexer);
}
flagLexerSpecified = false;
}
// If start as tray icon, set current filename as tooltip
if (flagStartAsTrayIcon) {
SetNotifyIconTitle(hwnd);
} else if (bInFullScreenMode) {
ToggleFullScreenMode();
}
bInitDone = true;
if (SciCall_GetLength() == 0) {
UpdateToolbar();
UpdateStatusbar();
}
if (notepadAction > NotepadReplacementAction_Default) {
PostMessage(hwnd, WM_COMMAND, MAKEWPARAM(IDM_FILE_PRINT, 1), notepadAction);
}
#if 0
watch.Stop();
watch.ShowLog("InitInstance() time");
#endif
}