-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenScript.cpp
More file actions
1427 lines (1260 loc) · 51 KB
/
Copy pathOpenScript.cpp
File metadata and controls
1427 lines (1260 loc) · 51 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
// OpenScript 1.5 - A simple script creator and editor
// This code is designed to be compiled with a C++17 compliant compiler and linked against the Windows API libraries.
// It provides basic text editing functionalities including file operations, find/replace, word wrap, font selection, and printing.
// Copyright (C) 2026 R.J. Dohnert
// This program is free software licensed under the BSD-3 Clause
// You can redistribute it and/or modify it under the terms of the BSD-3 Clause.
#include <windows.h>
#include <commdlg.h>
#include <string>
#include <algorithm>
#include <cwctype>
#include <shellapi.h>
#include <richedit.h>
#ifndef IDI_APP_ICON
#define IDI_APP_ICON 101
#endif
// Link essential Windows libraries (especially helpful for MSVC/VS Code)
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "comdlg32.lib")
// Shell functions (icon extraction)
#pragma comment(lib, "shell32.lib")
// Define Resources and Menu IDs
#define IDC_EDIT 1
#define IDC_LINE_NUMBERS 2
#define IDM_FILE_NEW 1001
#define IDM_FILE_OPEN 1002
#define IDM_FILE_SAVE 1003
#define IDM_FILE_SAVE_AS 1004
#define IDM_FILE_PRINT 1005
#define IDM_FILE_EXIT 1006
#define IDM_EDIT_FIND 1007
#define IDM_EDIT_REPLACE 1008
#define IDM_EDIT_LINE_NUMBERS 1012
#define IDM_HELP_ABOUT 1011
#define IDM_VIEW_SHOW_TERMINAL 1013
#define IDM_INSERT_CMD_IF 1014
#define IDM_INSERT_CMD_FOR 1015
#define IDM_INSERT_CMD_ECHO 1016
#define IDM_INSERT_CMD_POWERSHELL_FOREACH 1017
#define IDM_INSERT_VAR_ERRORLEVEL 1018
#define IDM_INSERT_VAR_BATCH_SCRIPT_DIR 1019
#define IDM_INSERT_VAR_PS_SCRIPT_ROOT 1020
#define IDM_INSERT_VAR_PS_PATH 1021
#define IDM_INSERT_CMD_CD 1022
#define IDM_INSERT_CMD_DIR 1023
#define IDM_INSERT_CMD_COPY 1024
#define IDM_INSERT_CMD_DEL 1025
#define IDM_INSERT_CMD_SET 1026
#define IDM_INSERT_CMD_PAUSE 1027
#define WM_APP_PROCESS_TERMINATED (WM_APP + 1)
// Common UI constants
static const int PRINT_MARGIN = 100;
// Global variables for window states
HWND hwndEdit = NULL;
HWND hwndLineNumbers = NULL;
HFONT hFont = NULL;
HWND hwndFindDlg = NULL;
UINT uFindReplaceMsg = 0;
FINDREPLACEW fr;
wchar_t szFindWhat[256] = L"";
wchar_t szReplaceWith[256] = L"";
wchar_t szFileName[MAX_PATH] = L"";
wchar_t szSettingsPath[MAX_PATH] = L"";
bool bWordWrap = true;
bool bShowLineNumbers = false;
bool bIsModified = false;
HICON hAppIcon = NULL;
HICON hAppIconSmall = NULL;
HMODULE g_hMsftEdit = NULL;
bool g_isApplyingHighlight = false;
HANDLE g_hWatchedProcess = NULL;
HANDLE g_hProcessExitWait = NULL;
// Subclass procedure and line number sync state
WNDPROC g_OriginalEditProc = NULL;
int g_prevLineCount = -1;
void CleanupProcessWatch() {
if (g_hProcessExitWait) {
UnregisterWaitEx(g_hProcessExitWait, INVALID_HANDLE_VALUE);
g_hProcessExitWait = NULL;
}
if (g_hWatchedProcess) {
CloseHandle(g_hWatchedProcess);
g_hWatchedProcess = NULL;
}
}
VOID CALLBACK OnWatchedProcessExit(PVOID context, BOOLEAN) {
HWND hwnd = (HWND)context;
if (hwnd) {
PostMessageW(hwnd, WM_APP_PROCESS_TERMINATED, 0, 0);
}
}
enum class ScriptLang {
None,
Batch,
Shell,
PowerShell
};
bool IsWordChar(wchar_t ch) {
return (std::iswalnum(ch) != 0) || ch == L'_' || ch == L'-';
}
bool IsKeyword(const std::wstring& token, const wchar_t* const* keywords, int count) {
for (int i = 0; i < count; ++i) {
if (token == keywords[i]) {
return true;
}
}
return false;
}
ScriptLang DetectScriptLanguage() {
if (wcslen(szFileName) == 0) return ScriptLang::None;
const wchar_t* dot = wcsrchr(szFileName, L'.');
if (!dot || dot[1] == L'\0') return ScriptLang::None;
std::wstring ext(dot + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), ::towlower);
if (ext == L"cmd" || ext == L"bat") return ScriptLang::Batch;
if (ext == L"sh" || ext == L"ksh") return ScriptLang::Shell;
if (ext == L"ps1") return ScriptLang::PowerShell;
return ScriptLang::None;
}
void ApplyColorRange(int start, int end, COLORREF color) {
if (end <= start) return;
CHARRANGE cr = { start, end };
SendMessageW(hwndEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
CHARFORMAT2W cf;
ZeroMemory(&cf, sizeof(cf));
cf.cbSize = sizeof(cf);
cf.dwMask = CFM_COLOR;
cf.crTextColor = color;
SendMessageW(hwndEdit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
}
void ApplySyntaxHighlighting() {
if (!hwndEdit || g_isApplyingHighlight) return;
ScriptLang lang = DetectScriptLanguage();
if (lang == ScriptLang::None) return;
int len = GetWindowTextLengthW(hwndEdit);
if (len <= 0 || len > 200000) return;
std::wstring text;
text.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], len + 1);
text.resize(copied);
static const wchar_t* batchKeywords[] = {
L"if", L"else", L"for", L"in", L"do", L"goto", L"call", L"set", L"setlocal", L"endlocal",
L"echo", L"pause", L"shift", L"exit", L"not", L"exist", L"defined", L"errorlevel", L"choice", L"timeout",
L"enabledelayedexpansion", L"disabledelayedexpansion", L"equ", L"neq", L"lss", L"leq", L"gtr", L"geq",
L"cmdextversion", L"verify", L"assoc", L"attrib", L"break", L"cd", L"chdir", L"cls", L"color", L"copy",
L"date", L"del", L"erase", L"dir", L"ftype", L"md", L"mkdir", L"mklink", L"move", L"path",
L"popd", L"prompt", L"pushd", L"rd", L"rmdir", L"ren", L"rename", L"start", L"title", L"type",
L"ver", L"vol", L"where", L"setx"
};
static const wchar_t* shellKeywords[] = {
L"if", L"then", L"else", L"elif", L"fi", L"for", L"while", L"do", L"done", L"case", L"esac",
L"function", L"in", L"select", L"until", L"break", L"continue", L"return", L"exit", L"local", L"export",
L"readonly", L"typeset", L"declare", L"integer", L"float", L"alias", L"unalias", L"unset", L"source",
L"exec", L"eval", L"trap", L"times", L"umask", L"wait", L"shift", L"getopts", L"set", L"test",
L"true", L"false", L"coproc", L"time", L"let", L"printf", L"read", L"mapfile", L"array", L"typeset"
};
static const wchar_t* psKeywords[] = {
L"if", L"else", L"elseif", L"switch", L"for", L"foreach", L"while", L"do", L"until", L"function",
L"filter", L"param", L"begin", L"process", L"end", L"return", L"break", L"continue", L"trap", L"throw",
L"try", L"catch", L"finally", L"in", L"data", L"dynamicparam", L"class", L"enum", L"hidden", L"using",
L"workflow", L"parallel", L"sequence", L"configuration", L"from", L"define", L"var", L"exit", L"default"
};
static const wchar_t* psCmdlets[] = {
L"get-item", L"set-item", L"new-item", L"remove-item", L"clear-item", L"copy-item", L"move-item", L"rename-item",
L"get-childitem", L"resolve-path", L"convert-path", L"join-path", L"split-path", L"test-path", L"new-psdrive", L"remove-psdrive",
L"get-content", L"set-content", L"add-content", L"clear-content", L"get-location", L"set-location", L"push-location", L"pop-location",
L"get-acl", L"set-acl", L"get-service", L"start-service", L"stop-service", L"restart-service", L"suspend-service", L"resume-service",
L"new-service", L"set-service", L"get-process", L"start-process", L"stop-process", L"wait-process", L"debug-process",
L"get-command", L"get-help", L"get-member", L"select-object", L"where-object", L"forEach-object", L"measure-object",
L"sort-object", L"group-object", L"compare-object", L"tee-object", L"new-object", L"add-member", L"get-variable", L"set-variable",
L"clear-variable", L"remove-variable", L"get-alias", L"set-alias", L"new-alias", L"export-alias", L"import-alias",
L"get-date", L"set-date", L"get-random", L"get-unique", L"write-output", L"write-host", L"write-warning", L"write-error",
L"write-verbose", L"write-debug", L"write-information", L"write-progress", L"read-host", L"out-host", L"out-file", L"out-string",
L"out-null", L"out-gridview", L"format-table", L"format-list", L"format-wide", L"format-custom", L"convertto-json", L"convertfrom-json",
L"convertto-csv", L"convertfrom-csv", L"export-csv", L"import-csv", L"convertto-xml", L"select-string", L"start-sleep", L"start-job",
L"stop-job", L"wait-job", L"receive-job", L"get-job", L"remove-job", L"invoke-command", L"invoke-expression", L"invoke-item",
L"get-history", L"add-history", L"clear-history", L"get-event", L"new-event", L"remove-event", L"get-eventsubscriber",
L"register-objectevent", L"unregister-event", L"get-psprovider", L"get-psdrive", L"get-module", L"import-module", L"remove-module",
L"new-module", L"find-module", L"install-module", L"update-module", L"save-module", L"publish-module", L"get-package", L"find-package",
L"install-package", L"uninstall-package", L"save-package", L"get-credential", L"get-culture", L"get-uiculture", L"get-timezone",
L"set-timezone", L"get-winuserlanguageList", L"set-winuserlanguageList", L"new-timespan", L"get-filehash", L"get-authenticodesignature",
L"set-authenticodesignature", L"expand-archive", L"compress-archive", L"get-computerinfo", L"get-hotfix", L"get-ciminstance",
L"new-cimsession", L"remove-cimsession", L"get-wmiobject", L"invoke-webrequest", L"invoke-restmethod", L"new-webserviceproxy",
L"enter-pssession", L"exit-pssession", L"new-pssession", L"remove-pssession", L"get-pssession", L"test-connection", L"get-netipaddress",
L"get-netadapter", L"get-dnsclientserveraddress", L"get-scheduledtask", L"register-scheduledtask", L"unregister-scheduledtask",
L"start-transcript", L"stop-transcript", L"set-executionpolicy", L"get-executionpolicy", L"about", L"help"
};
const wchar_t* const* keywords = NULL;
int keywordCount = 0;
const wchar_t* const* cmdlets = NULL;
int cmdletCount = 0;
if (lang == ScriptLang::Batch) {
keywords = batchKeywords;
keywordCount = (int)(sizeof(batchKeywords) / sizeof(batchKeywords[0]));
} else if (lang == ScriptLang::Shell) {
keywords = shellKeywords;
keywordCount = (int)(sizeof(shellKeywords) / sizeof(shellKeywords[0]));
} else {
keywords = psKeywords;
keywordCount = (int)(sizeof(psKeywords) / sizeof(psKeywords[0]));
cmdlets = psCmdlets;
cmdletCount = (int)(sizeof(psCmdlets) / sizeof(psCmdlets[0]));
}
const COLORREF defaultColor = RGB(0, 0, 0);
const COLORREF keywordColor = RGB(0, 0, 180);
const COLORREF cmdletColor = RGB(121, 94, 38);
const COLORREF stringColor = RGB(163, 21, 21);
const COLORREF commentColor = RGB(0, 128, 0);
g_isApplyingHighlight = true;
SendMessageW(hwndEdit, WM_SETREDRAW, FALSE, 0);
CHARRANGE savedSel;
SendMessageW(hwndEdit, EM_EXGETSEL, 0, (LPARAM)&savedSel);
ApplyColorRange(0, copied, defaultColor);
const int n = copied;
int i = 0;
while (i < n) {
bool lineStart = (i == 0 || text[i - 1] == L'\n');
if (lineStart && lang == ScriptLang::Batch) {
int j = i;
while (j < n && (text[j] == L' ' || text[j] == L'\t')) j++;
if (j + 1 < n && text[j] == L':' && text[j + 1] == L':') {
int k = j;
while (k < n && text[k] != L'\n') k++;
ApplyColorRange(j, k, commentColor);
i = k;
continue;
}
if (j + 2 < n) {
wchar_t c0 = (wchar_t)towlower(text[j]);
wchar_t c1 = (wchar_t)towlower(text[j + 1]);
wchar_t c2 = (wchar_t)towlower(text[j + 2]);
if (c0 == L'r' && c1 == L'e' && c2 == L'm') {
wchar_t next = (j + 3 < n) ? text[j + 3] : L'\n';
if (next == L' ' || next == L'\t' || next == L'\r' || next == L'\n') {
int k = j;
while (k < n && text[k] != L'\n') k++;
ApplyColorRange(j, k, commentColor);
i = k;
continue;
}
}
}
}
if ((lang == ScriptLang::Shell || lang == ScriptLang::PowerShell) && text[i] == L'#') {
int k = i;
while (k < n && text[k] != L'\n') k++;
ApplyColorRange(i, k, commentColor);
i = k;
continue;
}
bool isStringStart = false;
wchar_t quote = L'\0';
if (lang == ScriptLang::Batch) {
isStringStart = (text[i] == L'"');
quote = L'"';
} else {
isStringStart = (text[i] == L'"' || text[i] == L'\'');
quote = text[i];
}
if (isStringStart) {
int k = i + 1;
while (k < n) {
if (text[k] == quote) {
k++;
break;
}
if (text[k] == L'\\' && k + 1 < n) {
k += 2;
continue;
}
k++;
}
ApplyColorRange(i, k, stringColor);
i = k;
continue;
}
if (IsWordChar(text[i])) {
int start = i;
while (i < n && IsWordChar(text[i])) i++;
std::wstring token = text.substr(start, i - start);
std::transform(token.begin(), token.end(), token.begin(), ::towlower);
if (IsKeyword(token, keywords, keywordCount)) {
ApplyColorRange(start, i, keywordColor);
} else if (lang == ScriptLang::PowerShell && cmdlets && IsKeyword(token, cmdlets, cmdletCount)) {
ApplyColorRange(start, i, cmdletColor);
}
continue;
}
i++;
}
SendMessageW(hwndEdit, EM_EXSETSEL, 0, (LPARAM)&savedSel);
SendMessageW(hwndEdit, WM_SETREDRAW, TRUE, 0);
InvalidateRect(hwndEdit, NULL, TRUE);
g_isApplyingHighlight = false;
}
void InitializeSettingsPath() {
if (GetModuleFileNameW(NULL, szSettingsPath, MAX_PATH) == 0) {
wcscpy_s(szSettingsPath, L"openscript.ini");
return;
}
wchar_t* lastSlash = wcsrchr(szSettingsPath, L'\\');
if (lastSlash) {
*(lastSlash + 1) = L'\0';
wcscat_s(szSettingsPath, L"openscript.ini");
} else {
wcscpy_s(szSettingsPath, L"openscript.ini");
}
}
void LoadAppSettings() {
bShowLineNumbers = GetPrivateProfileIntW(L"View", L"LineNumbers", 0, szSettingsPath) != 0;
}
void SaveAppSettings() {
WritePrivateProfileStringW(L"View", L"LineNumbers", bShowLineNumbers ? L"1" : L"0", szSettingsPath);
}
int GetLineNumberGutterWidth(HWND hwndParent) {
int lineCount = (int)SendMessageW(hwndEdit, EM_GETLINECOUNT, 0, 0);
if (lineCount < 1) lineCount = 1;
int digits = 1;
int temp = lineCount;
while (temp >= 10) {
temp /= 10;
digits++;
}
HDC hdc = GetDC(hwndParent);
HFONT hOldFont = NULL;
if (hFont) {
hOldFont = (HFONT)SelectObject(hdc, hFont);
}
TEXTMETRICW tm;
GetTextMetricsW(hdc, &tm);
if (hOldFont) {
SelectObject(hdc, hOldFont);
}
ReleaseDC(hwndParent, hdc);
return 12 + (digits * tm.tmAveCharWidth) + 8;
}
void LayoutEditorControls(HWND hwndParent) {
RECT rect;
GetClientRect(hwndParent, &rect);
if (bShowLineNumbers && hwndLineNumbers) {
int gutterWidth = GetLineNumberGutterWidth(hwndParent);
MoveWindow(hwndLineNumbers, 0, 0, gutterWidth, rect.bottom, TRUE);
ShowWindow(hwndLineNumbers, SW_SHOW);
MoveWindow(hwndEdit, gutterWidth, 0, rect.right - gutterWidth, rect.bottom, TRUE);
} else {
if (hwndLineNumbers) {
ShowWindow(hwndLineNumbers, SW_HIDE);
}
MoveWindow(hwndEdit, 0, 0, rect.right, rect.bottom, TRUE);
}
}
void SyncLineNumberScroll() {
if (!bShowLineNumbers || !hwndLineNumbers || !hwndEdit) return;
int firstMain = (int)SendMessageW(hwndEdit, EM_GETFIRSTVISIBLELINE, 0, 0);
int firstNums = (int)SendMessageW(hwndLineNumbers, EM_GETFIRSTVISIBLELINE, 0, 0);
int delta = firstMain - firstNums;
if (delta != 0) {
SendMessageW(hwndLineNumbers, EM_LINESCROLL, 0, delta);
}
}
LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (!g_OriginalEditProc) {
return DefWindowProcW(hwnd, message, wParam, lParam);
}
LRESULT res = CallWindowProcW(g_OriginalEditProc, hwnd, message, wParam, lParam);
// Sync line number scrolling after relevant messages are processed
if (message == WM_VSCROLL || message == WM_MOUSEWHEEL ||
message == WM_KEYDOWN || message == WM_KEYUP ||
message == WM_LBUTTONDOWN || message == WM_LBUTTONUP ||
message == WM_MOUSEMOVE) {
SyncLineNumberScroll();
}
return res;
}
void UpdateLineNumbers(HWND hwndParent) {
if (!hwndLineNumbers || !hwndEdit) return;
int textLen = GetWindowTextLengthW(hwndEdit);
std::wstring text;
if (textLen > 0) {
text.resize(textLen + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], textLen + 1);
text.resize(copied);
}
int lineCount = (int)SendMessageW(hwndEdit, EM_GETLINECOUNT, 0, 0);
if (lineCount < 1) lineCount = 1;
std::wstring numbers;
numbers.reserve(lineCount * 6);
int currentLogicalLine = 1;
wchar_t lineNum[32];
for (int i = 0; i < lineCount; ++i) {
int charIndex = (int)SendMessageW(hwndEdit, EM_LINEINDEX, i, 0);
bool isNewLogicalLine = false;
if (charIndex == 0) {
isNewLogicalLine = true;
} else if (charIndex > 0 && charIndex <= (int)text.length()) {
if (text[charIndex - 1] == L'\n') {
isNewLogicalLine = true;
}
}
if (isNewLogicalLine) {
swprintf_s(lineNum, L"%d\r\n", currentLogicalLine);
numbers += lineNum;
currentLogicalLine++;
} else {
numbers += L"\r\n";
}
}
int currentLen = GetWindowTextLengthW(hwndLineNumbers);
std::wstring currentNumbers;
if (currentLen > 0) {
currentNumbers.resize(currentLen + 1);
int copied = GetWindowTextW(hwndLineNumbers, ¤tNumbers[0], currentLen + 1);
currentNumbers.resize(copied);
}
if (numbers != currentNumbers) {
SetWindowTextW(hwndLineNumbers, numbers.c_str());
LayoutEditorControls(hwndParent);
}
SyncLineNumberScroll();
}
// Conversion helper: UTF-8 standard string to Wide UTF-16
std::wstring Utf8ToWstring(const std::string& str) {
if (str.empty()) return L"";
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
// Conversion helper: Wide UTF-16 to UTF-8 standard string
std::string WstringToUtf8(const std::wstring& wstr) {
if (wstr.empty()) return "";
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
// Update the application's title bar based on current open file
void UpdateWindowTitle(HWND hwnd) {
std::wstring title = L"OpenScript 1.5";
std::wstring prefix = bIsModified ? L"*" : L"";
if (wcslen(szFileName) > 0) {
wchar_t* p = wcsrchr(szFileName, L'\\');
if (p) {
title = prefix + (p + 1) + L" - " + title;
} else {
title = prefix + szFileName + L" - " + title;
}
} else {
title = prefix + L"Untitled - " + title;
}
SetWindowTextW(hwnd, title.c_str());
}
void LoadFile(HWND hwnd, const wchar_t* filePath) {
wchar_t szFullPath[MAX_PATH];
DWORD retval = GetFullPathNameW(filePath, MAX_PATH, szFullPath, NULL);
const wchar_t* targetPath = (retval > 0 && retval < MAX_PATH) ? szFullPath : filePath;
HANDLE hFile = CreateFileW(targetPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwSize = GetFileSize(hFile, NULL);
if (dwSize != INVALID_FILE_SIZE) {
// Safeguard against opening files larger than 20MB
if (dwSize > 20 * 1024 * 1024) {
MessageBoxW(hwnd, L"File is too large to open in OpenScript (limit is 20 MB).", L"Error", MB_OK | MB_ICONERROR);
CloseHandle(hFile);
return;
}
std::string buffer(dwSize, '\0');
DWORD dwRead;
if (ReadFile(hFile, &buffer[0], dwSize, &dwRead, NULL)) {
buffer.resize(dwRead);
// Strip UTF-8 BOM if present (\xEF\xBB\xBF)
if (buffer.size() >= 3 &&
(unsigned char)buffer[0] == 0xEF &&
(unsigned char)buffer[1] == 0xBB &&
(unsigned char)buffer[2] == 0xBF) {
buffer.erase(0, 3);
}
std::wstring wtext = Utf8ToWstring(buffer);
SetWindowTextW(hwndEdit, wtext.c_str());
wcscpy_s(szFileName, targetPath);
bIsModified = false;
g_prevLineCount = -1; // Reset gutter line count cache to force update
UpdateWindowTitle(hwnd);
ApplySyntaxHighlighting();
} else {
MessageBoxW(hwnd, L"Failed to read file.", L"Error", MB_OK | MB_ICONERROR);
}
} else {
MessageBoxW(hwnd, L"Failed to get file size.", L"Error", MB_OK | MB_ICONERROR);
}
CloseHandle(hFile);
} else {
MessageBoxW(hwnd, L"Failed to open file.", L"Error", MB_OK | MB_ICONERROR);
}
}
// Dialog helper to open standard files
void DoFileOpen(HWND hwnd) {
OPENFILENAMEW ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFilter =
L"Script Files (*.ksh;*.cmd;*.bat;*.sh;*.ps1)\0*.ksh;*.cmd;*.bat;*.sh;*.ps1\0"
L"Text Files (*.txt)\0*.txt\0"
L"All Files (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = L"txt";
if (GetOpenFileNameW(&ofn)) {
LoadFile(hwnd, szFileName);
}
}
// Dialog helper to save standard files. Returns true if saved, false if cancelled/failed.
bool DoFileSave(HWND hwnd, bool bSaveAs) {
if (bSaveAs || wcslen(szFileName) == 0) {
OPENFILENAMEW ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFilter =
L"Script Files (*.ksh;*.cmd;*.bat;*.sh;*.ps1)\0*.ksh;*.cmd;*.bat;*.sh;*.ps1\0"
L"Text Files (*.txt)\0*.txt\0"
L"All Files (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
ofn.lpstrDefExt = L"txt";
if (!GetSaveFileNameW(&ofn)) {
return false;
}
}
int len = GetWindowTextLengthW(hwndEdit);
std::wstring wtext;
if (len > 0) {
wtext.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &wtext[0], len + 1);
wtext.resize(copied);
}
std::string text = WstringToUtf8(wtext);
HANDLE hFile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwWritten;
BOOL bSuccess = WriteFile(hFile, text.c_str(), (DWORD)text.size(), &dwWritten, NULL);
CloseHandle(hFile);
if (bSuccess) {
bIsModified = false;
UpdateWindowTitle(hwnd);
return true;
} else {
MessageBoxW(hwnd, L"Failed to write to file.", L"Error", MB_OK | MB_ICONERROR);
}
} else {
MessageBoxW(hwnd, L"Failed to create file.", L"Error", MB_OK | MB_ICONERROR);
}
return false;
}
// Perform simple case-sensitive or insensitive text searches
void DoFindText(LPFINDREPLACEW lpfr) {
int len = GetWindowTextLengthW(hwndEdit);
std::wstring text;
if (len > 0) {
text.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], len + 1);
text.resize(copied);
}
DWORD startSel, endSel;
SendMessageW(hwndEdit, EM_GETSEL, (WPARAM)&startSel, (LPARAM)&endSel);
std::wstring searchStr(lpfr->lpstrFindWhat);
if (searchStr.empty()) return;
size_t startPos = 0;
bool bDown = (lpfr->Flags & FR_DOWN) != 0;
bool bMatchCase = (lpfr->Flags & FR_MATCHCASE) != 0;
std::wstring textToSearch = text;
std::wstring query = searchStr;
if (!bMatchCase) {
std::transform(textToSearch.begin(), textToSearch.end(), textToSearch.begin(), ::towlower);
std::transform(query.begin(), query.end(), query.begin(), ::towlower);
}
size_t foundPos = std::wstring::npos;
if (bDown) {
startPos = (startSel == endSel) ? startSel : endSel;
if (startPos < textToSearch.length()) {
foundPos = textToSearch.find(query, startPos);
}
} else {
startPos = startSel;
if (startPos > 0) {
foundPos = textToSearch.rfind(query, startPos - 1);
}
}
if (foundPos != std::wstring::npos) {
SendMessageW(hwndEdit, EM_SETSEL, foundPos, foundPos + query.length());
SendMessageW(hwndEdit, EM_SCROLLCARET, 0, 0);
SetFocus(hwndEdit);
} else {
MessageBoxW(lpfr->hwndOwner, L"Cannot find text.", L"Find", MB_OK | MB_ICONINFORMATION);
}
}
// Find and replace text at current selection
void DoReplaceText(LPFINDREPLACEW lpfr) {
DWORD startSel, endSel;
SendMessageW(hwndEdit, EM_GETSEL, (WPARAM)&startSel, (LPARAM)&endSel);
int len = GetWindowTextLengthW(hwndEdit);
std::wstring text;
if (len > 0) {
text.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], len + 1);
text.resize(copied);
}
std::wstring searchStr(lpfr->lpstrFindWhat);
std::wstring replaceStr(lpfr->lpstrReplaceWith);
bool bMatchCase = (lpfr->Flags & FR_MATCHCASE) != 0;
if (startSel != endSel && endSel <= text.length()) {
std::wstring selText = text.substr(startSel, endSel - startSel);
std::wstring matchText = selText;
std::wstring query = searchStr;
if (!bMatchCase) {
std::transform(matchText.begin(), matchText.end(), matchText.begin(), ::towlower);
std::transform(query.begin(), query.end(), query.begin(), ::towlower);
}
if (matchText == query) {
SendMessageW(hwndEdit, EM_REPLACESEL, TRUE, (LPARAM)replaceStr.c_str());
}
}
DoFindText(lpfr);
}
// Global find and replace all matches
void DoReplaceAllText(LPFINDREPLACEW lpfr) {
int len = GetWindowTextLengthW(hwndEdit);
std::wstring text;
if (len > 0) {
text.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], len + 1);
text.resize(copied);
}
std::wstring searchStr(lpfr->lpstrFindWhat);
std::wstring replaceStr(lpfr->lpstrReplaceWith);
if (searchStr.empty()) return;
bool bMatchCase = (lpfr->Flags & FR_MATCHCASE) != 0;
std::wstring textToSearch = text;
std::wstring query = searchStr;
if (!bMatchCase) {
std::transform(textToSearch.begin(), textToSearch.end(), textToSearch.begin(), ::towlower);
std::transform(query.begin(), query.end(), query.begin(), ::towlower);
}
std::wstring newText;
size_t currentPos = 0;
size_t foundPos = textToSearch.find(query, currentPos);
int replaceCount = 0;
while (foundPos != std::wstring::npos) {
newText += text.substr(currentPos, foundPos - currentPos);
newText += replaceStr;
currentPos = foundPos + query.length();
foundPos = textToSearch.find(query, currentPos);
replaceCount++;
}
newText += text.substr(currentPos);
if (replaceCount > 0) {
SetWindowTextW(hwndEdit, newText.c_str());
bIsModified = true;
wchar_t msg[128];
swprintf_s(msg, L"Replaced %d occurrences.", replaceCount);
MessageBoxW(lpfr->hwndOwner, msg, L"Replace All", MB_OK | MB_ICONINFORMATION);
} else {
MessageBoxW(lpfr->hwndOwner, L"Cannot find text to replace.", L"Replace All", MB_OK | MB_ICONINFORMATION);
}
}
// Instantiate Modeless Find Dialog
void ShowFindDialog(HWND hwnd) {
if (hwndFindDlg) {
SetFocus(hwndFindDlg);
return;
}
ZeroMemory(&fr, sizeof(fr));
fr.lStructSize = sizeof(fr);
fr.hwndOwner = hwnd;
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = sizeof(szFindWhat) / sizeof(wchar_t);
fr.Flags = FR_DOWN;
hwndFindDlg = FindTextW(&fr);
}
// Instantiate Modeless Replace Dialog
void ShowReplaceDialog(HWND hwnd) {
if (hwndFindDlg) {
SetFocus(hwndFindDlg);
return;
}
ZeroMemory(&fr, sizeof(fr));
fr.lStructSize = sizeof(fr);
fr.hwndOwner = hwnd;
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = sizeof(szFindWhat) / sizeof(wchar_t);
fr.lpstrReplaceWith = szReplaceWith;
fr.wReplaceWithLen = sizeof(szReplaceWith) / sizeof(wchar_t);
fr.Flags = FR_DOWN;
hwndFindDlg = ReplaceTextW(&fr);
}
// Print text using Windows GDI, adjusting for high-DPI printer metrics and margins
void DoFilePrint(HWND hwnd) {
PRINTDLGW pd;
ZeroMemory(&pd, sizeof(pd));
pd.lStructSize = sizeof(pd);
pd.hwndOwner = hwnd;
pd.Flags = PD_RETURNDC | PD_NOPAGENUMS | PD_NOSELECTION;
if (PrintDlgW(&pd)) {
DOCINFOW di = { sizeof(DOCINFOW), L"Text Editor Print Output" };
if (StartDocW(pd.hDC, &di) > 0) {
StartPage(pd.hDC);
LOGFONTW lf;
if (hFont == NULL || GetObjectW(hFont, sizeof(LOGFONTW), &lf) == 0) {
// Fall back to a default GUI font if the editor font is unavailable
GetObjectW(GetStockObject(DEFAULT_GUI_FONT), sizeof(LOGFONTW), &lf);
}
HDC hScreenDC = GetDC(NULL);
int screenY = GetDeviceCaps(hScreenDC, LOGPIXELSY);
int printY = GetDeviceCaps(pd.hDC, LOGPIXELSY);
ReleaseDC(NULL, hScreenDC);
// Scale screen-font sizes to printer units
lf.lfHeight = MulDiv(lf.lfHeight, printY, screenY);
lf.lfWidth = 0;
HFONT hPrintFont = CreateFontIndirectW(&lf);
HFONT hOldFont = NULL;
if (hPrintFont) {
hOldFont = (HFONT)SelectObject(pd.hDC, hPrintFont);
}
TEXTMETRICW tm;
GetTextMetricsW(pd.hDC, &tm);
int lineHeight = tm.tmHeight + tm.tmExternalLeading;
int pageHeight = GetDeviceCaps(pd.hDC, VERTRES);
int pageWidth = GetDeviceCaps(pd.hDC, HORZRES);
int y = PRINT_MARGIN; // Top margin offset
int len = GetWindowTextLengthW(hwndEdit);
std::wstring text;
if (len > 0) {
text.resize(len + 1);
int copied = GetWindowTextW(hwndEdit, &text[0], len + 1);
text.resize(copied);
}
std::wstring line;
size_t start = 0;
size_t end = 0;
while ((end = text.find(L'\n', start)) != std::wstring::npos) {
line = text.substr(start, end - start);
if (!line.empty() && line.back() == L'\r') {
line.pop_back();
}
if (line.empty()) {
y += lineHeight;
if (y > pageHeight - PRINT_MARGIN) {
EndPage(pd.hDC);
StartPage(pd.hDC);
y = PRINT_MARGIN;
}
} else {
RECT rect = { PRINT_MARGIN, y, pageWidth - PRINT_MARGIN, pageHeight - PRINT_MARGIN };
int heightUsed = DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK | DT_CALCRECT);
if (y + heightUsed > pageHeight - PRINT_MARGIN) {
EndPage(pd.hDC);
StartPage(pd.hDC);
y = PRINT_MARGIN;
rect.top = y;
rect.bottom = pageHeight - PRINT_MARGIN;
heightUsed = DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK | DT_CALCRECT);
}
DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK);
y += heightUsed;
}
start = end + 1;
}
if (start < text.length()) {
line = text.substr(start);
if (!line.empty()) {
RECT rect = { PRINT_MARGIN, y, pageWidth - PRINT_MARGIN, pageHeight - PRINT_MARGIN };
int heightUsed = DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK | DT_CALCRECT);
if (y + heightUsed > pageHeight - PRINT_MARGIN) {
EndPage(pd.hDC);
StartPage(pd.hDC);
y = PRINT_MARGIN;
rect.top = y;
rect.bottom = pageHeight - PRINT_MARGIN;
heightUsed = DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK | DT_CALCRECT);
}
DrawTextW(pd.hDC, line.c_str(), (int)line.length(), &rect, DT_WORDBREAK);
}
}
EndPage(pd.hDC);
EndDoc(pd.hDC);
if (hOldFont) SelectObject(pd.hDC, hOldFont);
if (hPrintFont) DeleteObject(hPrintFont);
}
DeleteDC(pd.hDC);
}
if (pd.hDevMode != NULL) GlobalFree(pd.hDevMode);
if (pd.hDevNames != NULL) GlobalFree(pd.hDevNames);
}
void ShowTestingTerminal(HWND hwnd) {
wchar_t workingDir[MAX_PATH] = {0};
if (wcslen(szFileName) > 0) {
wcscpy_s(workingDir, szFileName);
wchar_t* slash = wcsrchr(workingDir, L'\\');
if (slash) {
*slash = L'\0';
}
}
if (workingDir[0] == L'\0') {
if (GetModuleFileNameW(NULL, workingDir, MAX_PATH) > 0) {
wchar_t* slash = wcsrchr(workingDir, L'\\');
if (slash) {
*slash = L'\0';
}
}
}
wchar_t cmdLine[] =
L"cmd.exe /K title OpenScript Test Terminal && "
L"echo Terminal ready for script testing. && "
L"echo Use this window to run .cmd, .bat, .ps1, .sh, or .ksh files.";
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
BOOL created = CreateProcessW(
NULL,
cmdLine,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE,
NULL,
workingDir[0] ? workingDir : NULL,
&si,
&pi
);
if (!created) {
MessageBoxW(hwnd, L"Failed to open test terminal.", L"Terminal", MB_OK | MB_ICONERROR);
return;
}
CleanupProcessWatch();
CloseHandle(pi.hThread);
g_hWatchedProcess = pi.hProcess;
if (!RegisterWaitForSingleObject(
&g_hProcessExitWait,
g_hWatchedProcess,
OnWatchedProcessExit,
hwnd,
INFINITE,
WT_EXECUTEONLYONCE
)) {
CleanupProcessWatch();
MessageBoxW(hwnd, L"Unable to monitor terminal process.", L"Terminal", MB_OK | MB_ICONERROR);
}
}
void InsertTextAtCaret(const wchar_t* text) {
if (!hwndEdit || !text) return;
SendMessageW(hwndEdit, EM_REPLACESEL, TRUE, (LPARAM)text);
SetFocus(hwndEdit);
}
// Window Event Dispatcher
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == uFindReplaceMsg && uFindReplaceMsg != 0) {
LPFINDREPLACEW lpfr = (LPFINDREPLACEW)lParam;
if (lpfr->Flags & FR_DIALOGTERM) {
hwndFindDlg = NULL;
return 0;