Repository navigation
Expand file tree
/
Copy pathOpenScript.cpp
More file actions
2154 lines (1898 loc) · 77.7 KB
/
Copy pathOpenScript.cpp
File metadata and controls
2154 lines (1898 loc) · 77.7 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.
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <commdlg.h>
#include <commctrl.h>
#include <process.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cwctype>
#include <shellapi.h>
#include <shlobj.h>
#include <richedit.h>
#include <dwmapi.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")
#pragma comment(lib, "comctl32.lib")
// Shell functions (icon extraction, AppData path)
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "dwmapi.lib")
// Define Resources and Menu IDs
#define IDC_EDIT 1
#define IDC_LINE_NUMBERS 2
#define IDC_TAB_CONTROL 3
#define IDC_TERMINAL_PANEL 4
#define IDC_TERMINAL_OUTPUT 5
#define IDC_TERMINAL_INPUT 6
#define IDC_TERMINAL_BTN_RUN 7
#define IDC_TERMINAL_BTN_CLEAR 8
#define IDC_TERMINAL_BTN_HIDE 9
#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 IDM_FILE_NEW_TAB 1028
#define IDM_FILE_CLOSE_TAB 1029
#define WM_APP_PROCESS_TERMINATED (WM_APP + 1)
#define WM_APP_TERM_OUTPUT (WM_APP + 2)
#define IDT_SYNTAX_HIGHLIGHT 2001
static const UINT SYNTAX_HIGHLIGHT_DEBOUNCE_MS = 75;
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
// Common UI constants
static const int PRINT_MARGIN = 100;
// Document structure for Multi-Document Tabs
struct Document {
std::wstring filePath;
std::wstring title = L"Untitled";
std::wstring content;
bool isModified = false;
int scrollPos = 0;
int selStart = 0;
int selEnd = 0;
};
// Global variables for window states
HWND hwndEdit = NULL;
HWND hwndLineNumbers = NULL;
HWND hwndTab = NULL;
HWND hwndTerminalPanel = NULL;
HWND hwndTerminalOutput = NULL;
HWND hwndTerminalPrompt = NULL;
HWND hwndTerminalInput = NULL;
HWND hwndBtnRun = NULL;
HWND hwndBtnClear = NULL;
HWND hwndBtnHide = NULL;
HFONT hFont = NULL;
HFONT hTerminalFont = 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 bShowTerminal = false;
bool bIsModified = false;
HICON hAppIcon = NULL;
HICON hAppIconSmall = NULL;
HMODULE g_hMsftEdit = NULL;
bool g_isApplyingHighlight = false;
bool g_isSwitchingDoc = false;
HANDLE g_hWatchedProcess = NULL;
HANDLE g_hProcessExitWait = NULL;
// Terminal execution handles
HANDLE g_hTermPipeRead = NULL;
HANDLE g_hTermPipeWrite = NULL;
HANDLE g_hTermProcess = NULL;
HANDLE g_hTermThread = NULL;
WNDPROC g_OriginalTermInputProc = NULL;
// Document tabs state
std::vector<Document> g_documents;
int g_activeDocIndex = 0;
// Subclass procedure and line number state
WNDPROC g_OriginalEditProc = NULL;
int g_prevLineCount = -1;
std::vector<int> g_visualToLogicalLine;
int g_totalLogicalLines = 1;
int g_currentGutterWidth = 0;
LRESULT CALLBACK GutterWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK TerminalPanelWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK TerminalInputSubclassProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
void UpdateWindowTitle(HWND hwnd);
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 || g_isSwitchingDoc) 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 EnableImmersiveDarkMode(HWND hwnd) {
BOOL useDarkMode = TRUE;
// Try attribute 20 (Windows 11 / Windows 10 20H1+), fallback to 19 (Windows 10 1809/1903)
if (FAILED(DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &useDarkMode, sizeof(useDarkMode)))) {
DwmSetWindowAttribute(hwnd, 19, &useDarkMode, sizeof(useDarkMode));
}
}
void TriggerSyntaxHighlighting(HWND hwnd, bool immediate) {
if (immediate) {
KillTimer(hwnd, IDT_SYNTAX_HIGHLIGHT);
ApplySyntaxHighlighting();
} else {
SetTimer(hwnd, IDT_SYNTAX_HIGHLIGHT, SYNTAX_HIGHLIGHT_DEBOUNCE_MS, NULL);
}
}
void InitializeSettingsPath() {
// Check for portable mode: openscript.ini in the same directory as OpenScript.exe
wchar_t exePath[MAX_PATH] = {0};
if (GetModuleFileNameW(NULL, exePath, MAX_PATH) > 0) {
wchar_t* lastSlash = wcsrchr(exePath, L'\\');
if (lastSlash) {
*(lastSlash + 1) = L'\0';
std::wstring localIni = std::wstring(exePath) + L"openscript.ini";
DWORD attribs = GetFileAttributesW(localIni.c_str());
if (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY)) {
wcscpy_s(szSettingsPath, localIni.c_str());
return;
}
}
}
// Standard mode: %APPDATA%\OpenScript\openscript.ini
wchar_t appDataPath[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, appDataPath))) {
std::wstring appDir = std::wstring(appDataPath) + L"\\OpenScript";
CreateDirectoryW(appDir.c_str(), NULL);
std::wstring appIni = appDir + L"\\openscript.ini";
wcscpy_s(szSettingsPath, appIni.c_str());
return;
}
wcscpy_s(szSettingsPath, L"openscript.ini");
}
void LoadAppSettings() {
bShowLineNumbers = GetPrivateProfileIntW(L"View", L"LineNumbers", 1, szSettingsPath) != 0;
}
void SaveAppSettings() {
WritePrivateProfileStringW(L"View", L"LineNumbers", bShowLineNumbers ? L"1" : L"0", szSettingsPath);
}
void UpdateLogicalLines() {
g_visualToLogicalLine.clear();
if (!hwndEdit) {
g_totalLogicalLines = 1;
g_visualToLogicalLine.push_back(1);
return;
}
int visualLineCount = (int)SendMessageW(hwndEdit, EM_GETLINECOUNT, 0, 0);
if (visualLineCount < 1) visualLineCount = 1;
g_visualToLogicalLine.resize(visualLineCount, 0);
g_visualToLogicalLine[0] = 1;
int currentLogical = 1;
wchar_t ch[2] = {0};
TEXTRANGEW tr;
tr.lpstrText = ch;
for (int i = 1; i < visualLineCount; ++i) {
int charIndex = (int)SendMessageW(hwndEdit, EM_LINEINDEX, i, 0);
if (charIndex > 0) {
tr.chrg.cpMin = charIndex - 1;
tr.chrg.cpMax = charIndex;
ch[0] = L'\0';
SendMessageW(hwndEdit, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
if (ch[0] == L'\r' || ch[0] == L'\n') {
currentLogical++;
g_visualToLogicalLine[i] = currentLogical;
} else {
g_visualToLogicalLine[i] = 0; // Wrapped line continuation
}
} else {
currentLogical++;
g_visualToLogicalLine[i] = currentLogical;
}
}
g_totalLogicalLines = currentLogical;
}
int GetLineNumberGutterWidth(HWND hwndParent) {
int digits = 1;
int temp = (g_totalLogicalLines > 1) ? g_totalLogicalLines : 1;
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 14 + (digits * tm.tmAveCharWidth) + 8;
}
void LayoutTerminalControls(int width, int height) {
if (!hwndTerminalPanel) return;
int toolbarHeight = 28;
int inputHeight = 24;
int btnWidth = 110;
int btnSmall = 60;
int pad = 4;
// Toolbar buttons on top of panel
if (hwndBtnRun) MoveWindow(hwndBtnRun, width - btnWidth - btnSmall - btnSmall - pad * 3, 2, btnWidth, toolbarHeight - 4, TRUE);
if (hwndBtnClear) MoveWindow(hwndBtnClear, width - btnSmall - btnSmall - pad * 2, 2, btnSmall, toolbarHeight - 4, TRUE);
if (hwndBtnHide) MoveWindow(hwndBtnHide, width - btnSmall - pad, 2, btnSmall, toolbarHeight - 4, TRUE);
// Output area
int outHeight = height - toolbarHeight - inputHeight - pad;
if (outHeight < 30) outHeight = 30;
if (hwndTerminalOutput) MoveWindow(hwndTerminalOutput, 0, toolbarHeight, width, outHeight, TRUE);
// Input prompt and command edit at bottom
int promptWidth = 42;
if (hwndTerminalPrompt) MoveWindow(hwndTerminalPrompt, 4, height - inputHeight, promptWidth, inputHeight - 2, TRUE);
if (hwndTerminalInput) MoveWindow(hwndTerminalInput, promptWidth + 6, height - inputHeight, width - promptWidth - 10, inputHeight - 2, TRUE);
}
void LayoutEditorControls(HWND hwndParent) {
RECT rect;
GetClientRect(hwndParent, &rect);
int tabHeight = 28;
int termHeight = bShowTerminal ? 190 : 0;
int editorTop = tabHeight;
int editorHeight = rect.bottom - tabHeight - termHeight;
if (editorHeight < 30) editorHeight = 30;
if (hwndTab) {
MoveWindow(hwndTab, 0, 0, rect.right, tabHeight, TRUE);
}
if (bShowLineNumbers && hwndLineNumbers) {
int gutterWidth = GetLineNumberGutterWidth(hwndParent);
g_currentGutterWidth = gutterWidth;
MoveWindow(hwndLineNumbers, 0, editorTop, gutterWidth, editorHeight, TRUE);
ShowWindow(hwndLineNumbers, SW_SHOW);
MoveWindow(hwndEdit, gutterWidth, editorTop, rect.right - gutterWidth, editorHeight, TRUE);
} else {
if (hwndLineNumbers) {
ShowWindow(hwndLineNumbers, SW_HIDE);
}
MoveWindow(hwndEdit, 0, editorTop, rect.right, editorHeight, TRUE);
}
if (hwndTerminalPanel) {
if (bShowTerminal) {
int termTop = rect.bottom - termHeight;
MoveWindow(hwndTerminalPanel, 0, termTop, rect.right, termHeight, TRUE);
ShowWindow(hwndTerminalPanel, SW_SHOW);
LayoutTerminalControls(rect.right, termHeight);
} else {
ShowWindow(hwndTerminalPanel, SW_HIDE);
}
}
}
void UpdateLineNumbers(HWND hwndParent) {
if (!hwndEdit) return;
UpdateLogicalLines();
if (bShowLineNumbers && hwndLineNumbers) {
int newGutterWidth = GetLineNumberGutterWidth(hwndParent);
if (newGutterWidth != g_currentGutterWidth) {
LayoutEditorControls(hwndParent);
}
InvalidateRect(hwndLineNumbers, NULL, FALSE);
UpdateWindow(hwndLineNumbers);
}
}
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);
if (bShowLineNumbers && hwndLineNumbers && !g_isSwitchingDoc) {
if (message == WM_CHAR || message == WM_KEYUP || message == WM_PASTE ||
message == WM_CUT || message == WM_UNDO || message == WM_SETTEXT) {
UpdateLineNumbers(GetParent(hwnd));
} else if (message == WM_VSCROLL || message == WM_MOUSEWHEEL ||
message == WM_KEYDOWN ||
message == WM_LBUTTONDOWN || message == WM_LBUTTONUP ||
message == WM_MOUSEMOVE) {
InvalidateRect(hwndLineNumbers, NULL, FALSE);
}
}
return res;
}
LRESULT CALLBACK GutterWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_ERASEBKGND:
return 1;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_SETFOCUS:
if (hwndEdit) SetFocus(hwndEdit);
return 0;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rc;
GetClientRect(hwnd, &rc);
HDC memDC = CreateCompatibleDC(hdc);
HBITMAP memBmp = CreateCompatibleBitmap(hdc, rc.right, rc.bottom);
HBITMAP oldBmp = (HBITMAP)SelectObject(memDC, memBmp);
// Gutter background
HBRUSH bgBrush = CreateSolidBrush(RGB(245, 245, 245));
FillRect(memDC, &rc, bgBrush);
DeleteObject(bgBrush);
// Right border line
HPEN borderPen = CreatePen(PS_SOLID, 1, RGB(225, 225, 225));
HPEN oldPen = (HPEN)SelectObject(memDC, borderPen);
MoveToEx(memDC, rc.right - 1, 0, NULL);
LineTo(memDC, rc.right - 1, rc.bottom);
SelectObject(memDC, oldPen);
DeleteObject(borderPen);
if (hwndEdit && hFont) {
if (g_visualToLogicalLine.empty()) {
UpdateLogicalLines();
}
HFONT oldFont = (HFONT)SelectObject(memDC, hFont);
SetBkMode(memDC, TRANSPARENT);
SetTextColor(memDC, RGB(130, 130, 130));
TEXTMETRICW tm;
GetTextMetricsW(memDC, &tm);
int lineHeight = tm.tmHeight;
if (lineHeight < 1) lineHeight = 16;
RECT rcEditFormat;
ZeroMemory(&rcEditFormat, sizeof(rcEditFormat));
SendMessageW(hwndEdit, EM_GETRECT, 0, (LPARAM)&rcEditFormat);
int topOffset = rcEditFormat.top;
int firstVis = (int)SendMessageW(hwndEdit, EM_GETFIRSTVISIBLELINE, 0, 0);
int totalVisual = (int)g_visualToLogicalLine.size();
if (totalVisual < 1) totalVisual = 1;
int visIndex = 0;
for (int vLine = firstVis; vLine < totalVisual; ++vLine, ++visIndex) {
int charIndex = (int)SendMessageW(hwndEdit, EM_LINEINDEX, vLine, 0);
POINT pt = { -1, -1 };
if (charIndex >= 0) {
SendMessageW(hwndEdit, EM_POSFROMCHAR, (WPARAM)&pt, (LPARAM)charIndex);
}
int lineY = 0;
if (pt.y >= 0 && pt.y < rc.bottom + 50) {
lineY = pt.y;
} else {
lineY = topOffset + (visIndex * lineHeight);
}
if (lineY > rc.bottom) break;
int logNum = (vLine < (int)g_visualToLogicalLine.size()) ? g_visualToLogicalLine[vLine] : 0;
if (logNum > 0) {
wchar_t szNum[32];
swprintf_s(szNum, L"%d", logNum);
RECT rText = { 2, lineY, rc.right - 6, lineY + lineHeight };
DrawTextW(memDC, szNum, -1, &rText, DT_RIGHT | DT_SINGLELINE | DT_VCENTER);
}
}
SelectObject(memDC, oldFont);
}
BitBlt(hdc, 0, 0, rc.right, rc.bottom, memDC, 0, 0, SRCCOPY);
SelectObject(memDC, oldBmp);
DeleteObject(memBmp);
DeleteDC(memDC);
EndPaint(hwnd, &ps);
return 0;
}
default:
return DefWindowProcW(hwnd, message, wParam, lParam);
}
}
// Update Tab Title with modified marker
void UpdateTabTitle(int index) {
if (!hwndTab || index < 0 || index >= (int)g_documents.size()) return;
std::wstring display = g_documents[index].title;
if (g_documents[index].isModified) {
display += L" *";
}
TCITEMW tie;
ZeroMemory(&tie, sizeof(tie));
tie.mask = TCIF_TEXT;
tie.pszText = (LPWSTR)display.c_str();
tie.cchTextMax = (int)display.length();
SendMessageW(hwndTab, TCM_SETITEMW, (WPARAM)index, (LPARAM)&tie);
}
// Save the active document state from hwndEdit to g_documents[g_activeDocIndex]
void SaveActiveDocumentState() {
if (g_activeDocIndex >= 0 && g_activeDocIndex < (int)g_documents.size() && hwndEdit) {
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);
}
g_documents[g_activeDocIndex].content = text;
g_documents[g_activeDocIndex].filePath = szFileName;
g_documents[g_activeDocIndex].isModified = bIsModified;
DWORD startSel = 0, endSel = 0;
SendMessageW(hwndEdit, EM_GETSEL, (WPARAM)&startSel, (LPARAM)&endSel);
g_documents[g_activeDocIndex].selStart = (int)startSel;
g_documents[g_activeDocIndex].selEnd = (int)endSel;
}
}
int CreateNewDocument(const wchar_t* title = L"Untitled", const wchar_t* filePath = L"", const wchar_t* content = L"") {
Document doc;
doc.title = (title && wcslen(title) > 0) ? title : L"Untitled";
doc.filePath = filePath ? filePath : L"";
doc.content = content ? content : L"";
doc.isModified = false;
g_documents.push_back(doc);
int index = (int)g_documents.size() - 1;
if (hwndTab) {
std::wstring display = doc.title;
TCITEMW tie;
ZeroMemory(&tie, sizeof(tie));
tie.mask = TCIF_TEXT;
tie.pszText = (LPWSTR)display.c_str();
tie.cchTextMax = (int)display.length();
SendMessageW(hwndTab, TCM_INSERTITEMW, (WPARAM)index, (LPARAM)&tie);
}
return index;
}
void SwitchToDocument(HWND hwnd, int newIndex) {
if (newIndex < 0 || newIndex >= (int)g_documents.size() || !hwndEdit) return;
if (g_activeDocIndex != newIndex && g_activeDocIndex >= 0 && g_activeDocIndex < (int)g_documents.size()) {
SaveActiveDocumentState();
}
g_activeDocIndex = newIndex;
Document doc = g_documents[newIndex];
g_isSwitchingDoc = true;
wcscpy_s(szFileName, doc.filePath.c_str());
bIsModified = doc.isModified;
SetWindowTextW(hwndEdit, doc.content.c_str());
SendMessageW(hwndEdit, EM_SETSEL, doc.selStart, doc.selEnd);
SendMessageW(hwndEdit, EM_SCROLLCARET, 0, 0);
g_isSwitchingDoc = false;
if (hwndTab) {
SendMessageW(hwndTab, TCM_SETCURSEL, (WPARAM)newIndex, 0);
}
UpdateWindowTitle(hwnd);
UpdateLineNumbers(hwnd);
TriggerSyntaxHighlighting(hwnd, true);
UpdateTabTitle(newIndex);
}
// Forward declare DoFileSave
bool DoFileSave(HWND hwnd, bool bSaveAs);
bool CloseDocument(HWND hwnd, int index) {
if (index < 0 || index >= (int)g_documents.size()) return false;
if (g_documents[index].isModified) {
SwitchToDocument(hwnd, index);
wchar_t msg[300];
swprintf_s(msg, L"Do you want to save changes to %s?", g_documents[index].title.c_str());
int res = MessageBoxW(hwnd, msg, L"OpenScript", MB_YESNOCANCEL | MB_ICONQUESTION);
if (res == IDYES) {
if (!DoFileSave(hwnd, false)) return false;
} else if (res == IDCANCEL) {
return false;
}
}
if (hwndTab) {
SendMessageW(hwndTab, TCM_DELETEITEM, (WPARAM)index, 0);
}
g_documents.erase(g_documents.begin() + index);
if (g_documents.empty()) {
g_activeDocIndex = -1;
CreateNewDocument(L"Untitled", L"", L"");
SwitchToDocument(hwnd, 0);
} else {
int newIdx = (index >= (int)g_documents.size()) ? ((int)g_documents.size() - 1) : index;
g_activeDocIndex = -1;
SwitchToDocument(hwnd, newIdx);
}
return true;
}
// 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;
}
void AppendTerminalText(const wchar_t* text, COLORREF color = RGB(220, 220, 220)) {
if (!hwndTerminalOutput || !text) return;
int len = GetWindowTextLengthW(hwndTerminalOutput);
SendMessageW(hwndTerminalOutput, EM_SETSEL, len, len);
CHARFORMAT2W cf;
ZeroMemory(&cf, sizeof(cf));
cf.cbSize = sizeof(cf);
cf.dwMask = CFM_COLOR;
cf.crTextColor = color;
SendMessageW(hwndTerminalOutput, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
SendMessageW(hwndTerminalOutput, EM_REPLACESEL, FALSE, (LPARAM)text);
SendMessageW(hwndTerminalOutput, EM_SCROLLCARET, 0, 0);
}
void ClearTerminal() {
if (hwndTerminalOutput) {
SetWindowTextW(hwndTerminalOutput, L"");
AppendTerminalText(L"OpenScript Integrated Terminal [Version 1.5.0]\r\n", RGB(78, 201, 176));
AppendTerminalText(L"Ready. Click '▶ Run Script' (F5) or type commands below.\r\n\r\n", RGB(150, 150, 150));
}
}
unsigned __stdcall TerminalPipeReaderThread(void* param) {
HANDLE hPipe = (HANDLE)param;
char buffer[512];
DWORD bytesRead = 0;
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
buffer[bytesRead] = '\0';
std::wstring wchunk = Utf8ToWstring(std::string(buffer, bytesRead));
if (hwndTerminalOutput) {
AppendTerminalText(wchunk.c_str(), RGB(220, 220, 220));
}
}
CloseHandle(hPipe);
return 0;
}
void ExecuteTerminalCommand(const wchar_t* cmdStr) {
if (!cmdStr || wcslen(cmdStr) == 0) return;
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') {
GetCurrentDirectoryW(MAX_PATH, workingDir);
}
std::wstring echoHeader = L"\r\nPS " + std::wstring(workingDir) + L"> " + std::wstring(cmdStr) + L"\r\n";
AppendTerminalText(echoHeader.c_str(), RGB(86, 156, 214));
// Setup pipe
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE hReadPipe = NULL, hWritePipe = NULL;
if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) {
AppendTerminalText(L"Error: Failed to create terminal pipe.\r\n", RGB(244, 75, 75));
return;
}
SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
std::wstring fullCmd = L"cmd.exe /c " + std::wstring(cmdStr);
std::vector<wchar_t> cmdBuf(fullCmd.begin(), fullCmd.end());
cmdBuf.push_back(L'\0');
BOOL created = CreateProcessW(
NULL,
cmdBuf.data(),
NULL,
NULL,
TRUE,
CREATE_NO_WINDOW,
NULL,
workingDir[0] ? workingDir : NULL,
&si,
&pi
);
CloseHandle(hWritePipe);
if (created) {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
uintptr_t th = _beginthreadex(NULL, 0, TerminalPipeReaderThread, (void*)hReadPipe, 0, NULL);
if (th) CloseHandle((HANDLE)th);
} else {
CloseHandle(hReadPipe);
AppendTerminalText(L"Error: Failed to execute command.\r\n", RGB(244, 75, 75));
}
}
void ToggleTerminal(HWND hwnd);
void RunCurrentScriptInTerminal() {
if (!bShowTerminal) {
ToggleTerminal(GetParent(hwndTerminalPanel));
}
if (wcslen(szFileName) == 0) {
AppendTerminalText(L"\r\n[!] Please save the script file before executing it.\r\n", RGB(244, 180, 75));
return;
}
std::wstring ext = szFileName;
size_t dot = ext.rfind(L'.');
std::wstring extStr = (dot != std::wstring::npos) ? ext.substr(dot) : L"";
std::transform(extStr.begin(), extStr.end(), extStr.begin(), ::towlower);
std::wstring runCmd;
if (extStr == L".ps1") {
runCmd = L"powershell.exe -ExecutionPolicy Bypass -File \"" + std::wstring(szFileName) + L"\"";
} else if (extStr == L".bat" || extStr == L".cmd") {
runCmd = L"\"" + std::wstring(szFileName) + L"\"";
} else if (extStr == L".sh" || extStr == L".ksh") {