-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSource.cpp
More file actions
4125 lines (4112 loc) · 200 KB
/
Source.cpp
File metadata and controls
4125 lines (4112 loc) · 200 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
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#define NOMINMAX
#include <windows.h>
#include <shellapi.h>
#include <d3d11.h>
#include <dxgi1_2.h>
#include <d2d1_1.h>
#include <d2d1.h>
#include <dwrite.h>
#include <dcomp.h>
#include <imm.h>
#include <commdlg.h>
#include <commctrl.h>
#include <dwmapi.h>
#include <uxtheme.h>
#include <string>
#include <vector>
#include <memory>
#include <cassert>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <sstream>
#include <regex>
#include <cstring>
#include "compact_enc_det/compact_enc_det.h"
#include "resource.h"
#pragma comment(lib, "d2d1.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "dcomp.lib")
#pragma comment(lib, "dwrite.lib")
#pragma comment(lib, "imm32.lib")
#pragma comment(lib, "comdlg32.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "dwmapi.lib")
#pragma comment(lib, "uxtheme.lib")
#pragma comment(lib, "ced.lib")
const std::wstring APP_VERSION = L"miu v1.0.18";
enum MiuEncoding {
ENC_UTF8_NOBOM = 0,
ENC_UTF8_BOM,
ENC_UTF16LE,
ENC_UTF16BE,
ENC_LOCAL
};
struct DetectResult {
MiuEncoding type;
UINT codePage;
};
static void SwapBytes(wchar_t* buf, size_t count) {
for (size_t i = 0; i < count; ++i) {
unsigned short x = (unsigned short)buf[i];
buf[i] = (wchar_t)((x >> 8) | (x << 8));
}
}
static bool IsValidUtf8(const char* buf, size_t len) {
if (len == 0) return true;
size_t check_len = (len > 4096) ? 4096 : len;
size_t i = 0;
while (i < check_len) {
unsigned char c = buf[i];
if (c <= 0x7F) {
i++;
}
else if (c >= 0xC2 && c <= 0xDF) {
if (i + 1 >= check_len) break;
if ((buf[i + 1] & 0xC0) != 0x80) return false;
i += 2;
}
else if (c >= 0xE0 && c <= 0xEF) {
if (i + 2 >= check_len) break;
if ((buf[i + 1] & 0xC0) != 0x80 || (buf[i + 2] & 0xC0) != 0x80) return false;
i += 3;
}
else if (c >= 0xF0 && c <= 0xF4) {
if (i + 3 >= check_len) break;
if ((buf[i + 1] & 0xC0) != 0x80 || (buf[i + 2] & 0xC0) != 0x80 || (buf[i + 3] & 0xC0) != 0x80) return false;
i += 4;
}
else {
return false;
}
}
return true;
}
static UINT MapCedEncodingToCodePage(Encoding enc) {
switch (enc) {
case JAPANESE_SHIFT_JIS: return 932;
case JAPANESE_EUC_JP: return 51932;
case CHINESE_GB: return 936;
case CHINESE_BIG5: return 950;
case KOREAN_EUC_KR: return 949;
case RUSSIAN_CP1251: return 1251;
case LATIN1: return 1252;
case ASCII_7BIT: return CP_UTF8;
default: return CP_ACP;
}
}
static DetectResult DetectEncodingEx(const char* buf, size_t len) {
DetectResult res = { ENC_UTF8_NOBOM, CP_UTF8 };
if (len >= 3 && (unsigned char)buf[0] == 0xEF && (unsigned char)buf[1] == 0xBB && (unsigned char)buf[2] == 0xBF) {
res.type = ENC_UTF8_BOM; return res;
}
if (len >= 2) {
if ((unsigned char)buf[0] == 0xFF && (unsigned char)buf[1] == 0xFE) { res.type = ENC_UTF16LE; return res; }
if ((unsigned char)buf[0] == 0xFE && (unsigned char)buf[1] == 0xFF) { res.type = ENC_UTF16BE; return res; }
}
if (IsValidUtf8(buf, len)) {
res.type = ENC_UTF8_NOBOM; return res;
}
int bytes_consumed = 0;
bool is_reliable = false;
size_t ced_len = (len > 65536) ? 65536 : len;
Encoding ced_enc = CompactEncDet::DetectEncoding(
buf, static_cast<int>(ced_len),
nullptr, nullptr, nullptr,
UNKNOWN_ENCODING,
UNKNOWN_LANGUAGE,
CompactEncDet::WEB_CORPUS,
false,
&bytes_consumed,
&is_reliable
);
res.type = ENC_LOCAL;
res.codePage = MapCedEncodingToCodePage(ced_enc);
return res;
}
static std::wstring UTF8ToW(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), NULL, 0);
if (n <= 0) return {};
std::wstring w; w.resize(n);
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), &w[0], n);
return w;
}
static std::string LocalToUtf8(const char* data, size_t len, UINT cp) {
if (len == 0) return "";
int wLen = MultiByteToWideChar(cp, 0, data, (int)len, NULL, 0);
if (wLen <= 0) return "";
std::vector<wchar_t> wBuf(wLen);
MultiByteToWideChar(cp, 0, data, (int)len, wBuf.data(), wLen);
int uLen = WideCharToMultiByte(CP_UTF8, 0, wBuf.data(), wLen, NULL, 0, NULL, NULL);
if (uLen <= 0) return "";
std::string ret; ret.resize(uLen);
WideCharToMultiByte(CP_UTF8, 0, wBuf.data(), wLen, &ret[0], uLen, NULL, NULL);
return ret;
}
static std::string Utf8ToLocal(const std::string& utf8, UINT cp) {
if (utf8.empty()) return "";
std::wstring w = UTF8ToW(utf8);
int len = WideCharToMultiByte(cp, 0, w.c_str(), (int)w.size(), NULL, 0, NULL, NULL);
if (len <= 0) return "";
std::string ret; ret.resize(len);
WideCharToMultiByte(cp, 0, w.c_str(), (int)w.size(), &ret[0], len, NULL, NULL);
return ret;
}
static std::string Utf16ToUtf8(const char* data, size_t len, bool isBigEndian) {
if (len < 2) return "";
const wchar_t* wData = (const wchar_t*)(data + 2);
size_t wLen = (len - 2) / sizeof(wchar_t);
if (wLen == 0) return "";
std::vector<wchar_t> wBuf(wData, wData + wLen);
if (isBigEndian) {
SwapBytes(wBuf.data(), wBuf.size());
}
int uLen = WideCharToMultiByte(CP_UTF8, 0, wBuf.data(), (int)wBuf.size(), NULL, 0, NULL, NULL);
if (uLen <= 0) return "";
std::string ret;
ret.resize(uLen);
WideCharToMultiByte(CP_UTF8, 0, wBuf.data(), (int)wBuf.size(), &ret[0], uLen, NULL, NULL);
return ret;
}
static std::wstring Utf8ToUtf16(const std::string& utf8) {
if (utf8.empty()) return L"";
int wLen = MultiByteToWideChar(CP_UTF8, 0, utf8.data(), (int)utf8.size(), NULL, 0);
if (wLen <= 0) return L"";
std::wstring ret;
ret.resize(wLen);
MultiByteToWideChar(CP_UTF8, 0, utf8.data(), (int)utf8.size(), &ret[0], wLen);
return ret;
}
static std::wstring GetResString(UINT id) {
const wchar_t* pBuf = nullptr;
int len = LoadStringW(GetModuleHandle(NULL), id, (LPWSTR)&pBuf, 0);
if (len > 0 && pBuf) {
return std::wstring(pBuf, len);
}
return L"";
}
static std::string WToUTF8(const std::wstring& w) {
if (w.empty()) return {};
int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), NULL, 0, NULL, NULL);
if (n <= 0) return {};
std::string s; s.resize(n);
WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), &s[0], n, NULL, NULL);
return s;
}
static std::string UnescapeString(const std::string& s, const std::string& newline) {
std::string out;
out.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\\' && i + 1 < s.size()) {
switch (s[i + 1]) {
case 'n': out += newline; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case '\\': out += '\\'; break;
default: out += s[i]; out += s[i + 1]; break;
}
i++;
}
else {
out += s[i];
}
}
return out;
}
struct Piece { bool isOriginal; size_t start; size_t len; };
struct PieceTable {
const char* origPtr = nullptr; size_t origSize = 0;
std::string addBuf; std::vector<Piece> pieces;
void initFromFile(const char* data, size_t size) { origPtr = data; origSize = size; pieces.clear(); addBuf.clear(); if (size > 0) pieces.push_back({ true, 0, size }); }
void initEmpty() { origPtr = nullptr; origSize = 0; pieces.clear(); addBuf.clear(); }
size_t length() const { size_t s = 0; for (auto& p : pieces) s += p.len; return s; }
std::string getRange(size_t pos, size_t count) const {
std::string out; out.reserve(std::min(count, (size_t)4096));
size_t cur = 0;
for (const auto& p : pieces) {
if (cur + p.len <= pos) { cur += p.len; continue; }
size_t localStart = (pos > cur) ? (pos - cur) : 0;
size_t take = std::min(p.len - localStart, count - out.size());
if (take == 0) break;
if (p.isOriginal) out.append(origPtr + p.start + localStart, take);
else out.append(addBuf.data() + p.start + localStart, take);
if (out.size() >= count) break;
cur += p.len;
}
return out;
}
void insert(size_t pos, const std::string& s) {
if (s.empty()) return;
size_t cur = 0; size_t idx = 0;
while (idx < pieces.size() && cur + pieces[idx].len < pos) { cur += pieces[idx].len; ++idx; }
if (idx < pieces.size()) {
Piece p = pieces[idx];
size_t offsetInPiece = pos - cur;
if (offsetInPiece > 0 && offsetInPiece < p.len) {
pieces[idx] = { p.isOriginal, p.start, offsetInPiece };
pieces.insert(pieces.begin() + idx + 1, { p.isOriginal, p.start + offsetInPiece, p.len - offsetInPiece });
idx++;
}
else if (offsetInPiece == p.len) idx++;
}
else idx = pieces.size();
size_t addStart = addBuf.size(); addBuf.append(s);
pieces.insert(pieces.begin() + idx, { false, addStart, s.size() });
coalesceAround(idx);
}
void erase(size_t pos, size_t count) {
if (count == 0) return;
size_t cur = 0; size_t idx = 0;
while (idx < pieces.size() && cur + pieces[idx].len <= pos) { cur += pieces[idx].len; ++idx; }
size_t remaining = count;
if (idx >= pieces.size()) return;
if (pos > cur) {
Piece p = pieces[idx]; size_t leftLen = pos - cur;
pieces[idx] = { p.isOriginal, p.start, leftLen };
pieces.insert(pieces.begin() + idx + 1, { p.isOriginal, p.start + leftLen, p.len - leftLen });
idx++;
}
while (idx < pieces.size() && remaining > 0) {
if (pieces[idx].len <= remaining) { remaining -= pieces[idx].len; pieces.erase(pieces.begin() + idx); }
else { pieces[idx].start += remaining; pieces[idx].len -= remaining; remaining = 0; }
}
coalesceAround(idx > 0 ? idx - 1 : 0);
}
void coalesceAround(size_t idx) {
if (pieces.empty()) return;
if (idx >= pieces.size()) idx = pieces.size() - 1;
if (idx > 0) {
Piece& a = pieces[idx - 1]; Piece& b = pieces[idx];
if (!a.isOriginal && !b.isOriginal && (a.start + a.len == b.start)) { a.len += b.len; pieces.erase(pieces.begin() + idx); idx--; }
}
if (idx + 1 < pieces.size()) {
Piece& a = pieces[idx]; Piece& b = pieces[idx + 1];
if (!a.isOriginal && !b.isOriginal && (a.start + a.len == b.start)) { a.len += b.len; pieces.erase(pieces.begin() + idx + 1); }
}
}
char charAt(size_t pos) const {
size_t cur = 0;
for (const auto& p : pieces) {
if (cur + p.len <= pos) { cur += p.len; continue; }
size_t local = pos - cur;
if (p.isOriginal) return origPtr[p.start + local]; else return addBuf[p.start + local];
}
return ' ';
}
};
struct Cursor {
size_t head; size_t anchor; float desiredX;
size_t start() const { return std::min(head, anchor); }
size_t end() const { return std::max(head, anchor); }
bool hasSelection() const { return head != anchor; }
void clearSelection() { anchor = head; }
};
struct EditOp { enum Type { Insert, Erase } type; size_t pos; std::string text; };
struct EditBatch { std::vector<EditOp> ops; std::vector<Cursor> beforeCursors; std::vector<Cursor> afterCursors; };
struct UndoManager {
std::vector<EditBatch> undoStack; std::vector<EditBatch> redoStack; int savePoint = 0;
void clear() { undoStack.clear(); redoStack.clear(); savePoint = 0; }
void markSaved() { savePoint = (int)undoStack.size(); }
bool isModified() const { return (int)undoStack.size() != savePoint; }
void push(const EditBatch& batch) { if (savePoint > (int)undoStack.size()) savePoint = -1; undoStack.push_back(batch); redoStack.clear(); }
bool canUndo() const { return !undoStack.empty(); }
bool canRedo() const { return !redoStack.empty(); }
EditBatch popUndo() { EditBatch e = undoStack.back(); undoStack.pop_back(); redoStack.push_back(e); return e; }
EditBatch popRedo() { EditBatch e = redoStack.back(); redoStack.pop_back(); undoStack.push_back(e); return e; }
};
struct MappedFile {
HANDLE hFile = INVALID_HANDLE_VALUE; HANDLE hMap = NULL; const char* ptr = nullptr; size_t size = 0;
bool open(const wchar_t* path) {
hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return false;
LARGE_INTEGER li; if (!GetFileSizeEx(hFile, &li)) return false; size = (size_t)li.QuadPart;
if (size == 0) { ptr = nullptr; return true; }
hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (!hMap) return false; ptr = (const char*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0); return !!ptr;
}
void close() { if (ptr) { UnmapViewOfFile(ptr); ptr = nullptr; } if (hMap) { CloseHandle(hMap); hMap = NULL; } if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } }
~MappedFile() { close(); }
};
struct Editor {
HWND hwnd = NULL;
HICON hFileIcon = NULL;
HICON hAppIcon = NULL;
HWND hFindDlg = NULL;
PieceTable pt;
UndoManager undo;
std::unique_ptr<MappedFile> fileMap;
std::wstring currentFilePath;
bool isDirty = false;
UINT cfMsDevCol = 0;
UINT cfMsDevLine = 0;
std::regex cachedRegex;
bool isRegexDirty = true;
bool isRegexValid = false;
std::string searchQuery;
std::string replaceQuery;
bool searchMatchCase = false;
bool searchWholeWord = false;
bool searchRegex = false;
bool isReplaceMode = false;
bool showHelpPopup = false;
std::vector<Cursor> cursors;
EditBatch pendingPadding;
bool isDragging = false; bool isRectSelecting = false;
float rectAnchorX = 0, rectAnchorY = 0; float rectHeadX = 0, rectHeadY = 0;
bool isDragMovePending = false; bool isDragMoving = false;
size_t dragMoveSourceStart = 0; size_t dragMoveSourceEnd = 0; size_t dragMoveDestPos = 0;
wchar_t highSurrogate = 0; std::string imeComp;
int vScrollPos = 0; int hScrollPos = 0; std::vector<size_t> lineStarts;
float maxLineWidth = 100.0f; float gutterWidth = 50.0f;
DWORD lastClickTime = 0; int clickCount = 0; int lastClickX = 0, lastClickY = 0;
float currentFontSize = 21.0f; DWORD64 zoomPopupEndTime = 0; std::wstring zoomPopupText;
bool suppressUI = false;
ID2D1Factory1* d2dFactory = nullptr;
ID2D1DeviceContext* rend = nullptr;
IDXGISwapChain1* swapChain = nullptr;
ID2D1Bitmap1* targetBitmap = nullptr;
IDCompositionDevice* dcompDevice = nullptr;
IDCompositionTarget* dcompTarget = nullptr;
IDWriteFactory* dwFactory = nullptr;
IDWriteTextFormat* textFormat = nullptr; IDWriteTextFormat* popupTextFormat = nullptr;
IDWriteTextFormat* helpTextFormat = nullptr;
ID2D1StrokeStyle* dotStyle = nullptr; ID2D1StrokeStyle* roundJoinStyle = nullptr;
D2D1::ColorF background = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f); D2D1::ColorF textColor = D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f);
D2D1::ColorF gutterBg = D2D1::ColorF(0.95f, 0.95f, 0.95f, 1.0f); D2D1::ColorF gutterText = D2D1::ColorF(0.6f, 0.6f, 0.6f, 1.0f);
D2D1::ColorF selColor = D2D1::ColorF(0.7f, 0.8f, 1.0f, 1.0f); D2D1::ColorF highlightColor = D2D1::ColorF(1.0f, 1.0f, 0.0f, 0.4f);
float dpiScaleX = 1.0f, dpiScaleY = 1.0f; float lineHeight = 17.5f; float charWidth = 8.0f;
bool isFullScreen = false;
WINDOWPLACEMENT prevPlacement = { sizeof(WINDOWPLACEMENT) };
std::wstring helpTextStr;
D2D1::ColorF autoHlColor = D2D1::ColorF(0.8f, 0.8f, 0.8f, 0.35f);
D2D1::ColorF caretColor = D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f);
bool isDarkMode = false;
bool isOverwriteMode = false;
bool isVScrollDragging = false;
bool isHScrollDragging = false;
float scrollDragOffset = 0.0f;
bool isVScrollHover = false;
bool isHScrollHover = false;
bool isTrackingMouse = false;
MiuEncoding currentEncoding = ENC_UTF8_NOBOM;
UINT currentCodePage = CP_UTF8;
std::string convertedBuffer;
std::string newlineStr = "\r\n";
void updateSearchQuery(const std::string& newQuery) {
if (searchQuery != newQuery) {
searchQuery = newQuery;
isRegexDirty = true;
}
}
void updateSearchFlags(bool matchCase, bool wholeWord, bool regexMode) {
if (searchMatchCase != matchCase || searchWholeWord != wholeWord || searchRegex != regexMode) {
searchMatchCase = matchCase;
searchWholeWord = wholeWord;
searchRegex = regexMode;
isRegexDirty = true;
}
}
void ensureRegexReady() {
if (searchRegex && isRegexDirty) {
isRegexValid = false;
if (!searchQuery.empty()) {
try {
std::string actualQuery = preprocessRegexQuery(searchQuery);
std::regex_constants::syntax_option_type flags = std::regex_constants::ECMAScript;
if (!searchMatchCase) flags |= std::regex_constants::icase;
cachedRegex = std::regex(actualQuery, flags);
isRegexValid = true;
}
catch (...) {
isRegexValid = false;
}
}
isRegexDirty = false;
}
}
std::string preprocessRegexQuery(const std::string& query) {
std::string processed;
processed.reserve(query.size() * 4);
for (size_t i = 0; i < query.size(); ++i) {
char c = query[i];
if (c == '\\') {
if (i + 1 < query.size()) {
char next = query[i + 1];
if (next == 'n') {
bool isPrecededByCR = (i >= 2 && query[i - 2] == '\\' && query[i - 1] == 'r');
if (!isPrecededByCR) {
processed += "(?:\\r\\n|[\\r\\n])";
i++; continue;
}
}
processed += c; processed += next; i++; continue;
}
}
else if (c == '^') {
bool inClass = false;
if (i > 0 && query[i - 1] == '[') inClass = true;
if (!inClass) {
processed += "((?:^|(?:\\r\\n|\\r(?!\\n)|[\\n])))";
continue;
}
}
else if (c == '$') {
bool inClass = false;
if (i > 0 && query[i - 1] == '[') inClass = true;
if (!inClass) {
processed += "(?=(?:\\r\\n|[\\r\\n]|$))";
continue;
}
}
processed += c;
}
return processed;
}
void detectNewlineStyle(const char* buf, size_t len) {
size_t checkLen = (len > 4096) ? 4096 : len;
for (size_t i = 0; i < checkLen; ++i) {
if (buf[i] == '\r') {
if (i + 1 < checkLen && buf[i + 1] == '\n') {
newlineStr = "\r\n";
return;
}
newlineStr = "\r";
return;
}
else if (buf[i] == '\n') {
newlineStr = "\n";
return;
}
}
newlineStr = "\r\n";
}
bool checkSystemDarkMode() {
HKEY hKey;
DWORD val = 1;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExW(hKey, L"AppsUseLightTheme", NULL, NULL, (LPBYTE)&val, &size);
RegCloseKey(hKey);
}
return (val == 0);
}
D2D1::ColorF getWindowsAccentColor(float alpha) {
DWORD color = 0;
bool success = false;
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\DWM", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
DWORD type, size = sizeof(DWORD);
if (RegQueryValueExW(hKey, L"AccentColor", NULL, &type, (LPBYTE)&color, &size) == ERROR_SUCCESS) {
success = true;
}
RegCloseKey(hKey);
}
if (success) {
float r = (float)(color & 0xFF) / 255.0f;
float g = (float)((color >> 8) & 0xFF) / 255.0f;
float b = (float)((color >> 16) & 0xFF) / 255.0f;
return D2D1::ColorF(r, g, b, alpha);
}
return D2D1::ColorF(0.0f, 0.47f, 0.84f, alpha);
}
void updateThemeColors() {
isDarkMode = checkSystemDarkMode();
D2D1::ColorF accent = getWindowsAccentColor(0.5f);
bool isTransparencyEnabled = true;
HKEY hKey;
DWORD val = 1;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
if (RegQueryValueExW(hKey, L"EnableTransparency", NULL, NULL, (LPBYTE)&val, &size) == ERROR_SUCCESS) {
isTransparencyEnabled = (val != 0);
}
RegCloseKey(hKey);
}
int backdropValue = DWMSBT_TRANSIENTWINDOW;
bool isMicaEnabled = false;
if (isTransparencyEnabled) {
HRESULT hrMica = DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &backdropValue, sizeof(backdropValue));
isMicaEnabled = SUCCEEDED(hrMica);
}
float bgAlpha = isMicaEnabled ? 0.0f : 1.0f;
if (isDarkMode) {
background = D2D1::ColorF(0.0f, 0.0f, 0.0f, bgAlpha);
textColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
gutterBg = D2D1::ColorF(0.0f, 0.0f, 0.0f, bgAlpha);
gutterText = D2D1::ColorF(0.33f, 0.33f, 0.33f, 1.0f);
selColor = accent;
caretColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
autoHlColor = D2D1::ColorF(0.35f, 0.35f, 0.35f, 0.5f);
highlightColor = D2D1::ColorF(0.4f, 0.4f, 0.0f, 0.6f);
}
else {
background = D2D1::ColorF(1.0f, 1.0f, 1.0f, bgAlpha);
textColor = D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f);
gutterBg = D2D1::ColorF(1.0f, 1.0f, 1.0f, bgAlpha);
gutterText = D2D1::ColorF(0.66f, 0.66f, 0.66f, 1.0f);
selColor = accent;
caretColor = D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f);
autoHlColor = D2D1::ColorF(0.85f, 0.85f, 0.85f, 0.5f);
highlightColor = D2D1::ColorF(1.0f, 1.0f, 0.0f, 0.4f);
}
BOOL dark = isDarkMode;
DwmSetWindowAttribute(hwnd, 20, &dark, sizeof(dark));
if (isDarkMode) {
SetWindowTheme(hwnd, L"DarkMode_Explorer", NULL);
}
else {
SetWindowTheme(hwnd, L"Explorer", NULL);
}
if (hwnd) {
SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
InvalidateRect(hwnd, NULL, TRUE);
}
}
void handleDpiChange(float newDpiX, float newDpiY) {
dpiScaleX = newDpiX / 96.0f;
dpiScaleY = newDpiY / 96.0f;
if (rend) {
rend->SetDpi(newDpiX, newDpiY);
}
updateFont(currentFontSize);
rebuildLineStarts();
if (hwnd) InvalidateRect(hwnd, NULL, FALSE);
}
std::pair<std::string, bool> getHighlightTarget() {
if (cursors.size() > 1) return { "", false };
if (cursors.empty()) return { "", false };
const Cursor& c = cursors.back();
if (c.hasSelection()) {
size_t len = c.end() - c.start();
if (len == 0 || len > 200) return { "", false };
std::string s = pt.getRange(c.start(), len);
if (s.empty() || s.find('\n') != std::string::npos) return { "", false };
return { s, false };
}
size_t pos = c.head;
size_t len = pt.length();
if (pos > len) pos = len;
bool charRight = (pos < len && isWordChar(pt.charAt(pos)));
bool charLeft = (pos > 0 && isWordChar(pt.charAt(pos - 1)));
if (!charRight && !charLeft) return { "", true };
size_t start = pos;
size_t end = pos;
if (!charRight && charLeft) start--;
while (start > 0 && isWordChar(pt.charAt(start - 1))) start--;
while (end < len && isWordChar(pt.charAt(end))) end++;
if (end > start) return { pt.getRange(start, end - start), true };
return { "", true };
}
void initGraphics(HWND h) {
hwnd = h;
RECT rc; GetClientRect(hwnd, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
ID3D11Device* d3dDevice = nullptr;
ID3D11DeviceContext* d3dContext = nullptr;
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };
D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, creationFlags,
featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &d3dDevice, nullptr, &d3dContext);
IDXGIDevice* dxgiDevice = nullptr;
d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
D2D1_FACTORY_OPTIONS options = {};
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory1), &options, (void**)&d2dFactory);
ID2D1Device* d2dDevice = nullptr;
d2dFactory->CreateDevice(dxgiDevice, &d2dDevice);
d2dDevice->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &rend);
IDXGIFactory2* dxgiFactory = nullptr;
CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), (void**)&dxgiFactory);
DXGI_SWAP_CHAIN_DESC1 description = {};
description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
description.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
description.BufferCount = 2;
description.SampleDesc.Count = 1;
description.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
description.Scaling = DXGI_SCALING_STRETCH;
description.Width = width;
description.Height = height;
dxgiFactory->CreateSwapChainForComposition(dxgiDevice, &description, nullptr, &swapChain);
DCompositionCreateDevice(dxgiDevice, __uuidof(IDCompositionDevice), (void**)&dcompDevice);
dcompDevice->CreateTargetForHwnd(hwnd, TRUE, &dcompTarget);
IDCompositionVisual* dcompVisual = nullptr;
dcompDevice->CreateVisual(&dcompVisual);
dcompVisual->SetContent(swapChain);
dcompTarget->SetRoot(dcompVisual);
dcompDevice->Commit();
if (dcompVisual) dcompVisual->Release();
if (dxgiFactory) dxgiFactory->Release();
if (d2dDevice) d2dDevice->Release();
if (dxgiDevice) dxgiDevice->Release();
if (d3dContext) d3dContext->Release();
if (d3dDevice) d3dDevice->Release();
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown**>(&dwFactory));
UINT dpi = GetDpiForWindow(hwnd);
if (dpi == 0) dpi = 96;
FLOAT dpix = (FLOAT)dpi;
FLOAT dpiy = (FLOAT)dpi;
dpiScaleX = dpix / 96.0f;
dpiScaleY = dpiy / 96.0f;
rend->SetDpi(dpix, dpiy);
dwFactory->CreateTextFormat(L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 24.0f, L"en-us", &popupTextFormat);
if (popupTextFormat) { popupTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); popupTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); }
helpTextStr = APP_VERSION + GetResString(IDS_HELP_TEXT);
dwFactory->CreateTextFormat(L"Consolas", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 16.0f, L"en-us", &helpTextFormat);
if (helpTextFormat) {
helpTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
helpTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
}
float dashes[] = { 2.0f, 2.0f };
D2D1_STROKE_STYLE_PROPERTIES props = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_FLAT, D2D1_LINE_JOIN_MITER, 10.0f, D2D1_DASH_STYLE_CUSTOM, 0.0f); d2dFactory->CreateStrokeStyle(&props, dashes, 2, &dotStyle);
D2D1_STROKE_STYLE_PROPERTIES roundProps = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND, 10.0f, D2D1_DASH_STYLE_SOLID, 0.0f); d2dFactory->CreateStrokeStyle(&roundProps, nullptr, 0, &roundJoinStyle);
cfMsDevCol = RegisterClipboardFormatW(L"MSDEVColumnSelect");
cfMsDevLine = RegisterClipboardFormatW(L"MSDEVLineSelect");
hAppIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
updateThemeColors();
updateFont(currentFontSize);
rebuildLineStarts();
cursors.push_back({ 0, 0, 0.0f });
updateTitleBar();
updateWindowIcon();
}
void updateFont(float size) {
size = std::round(size);
if (size < 6.0f) size = 6.0f;
if (size > 200.0f) size = 200.0f;
if (textFormat && size == currentFontSize) return;
currentFontSize = size;
if (textFormat) { textFormat->Release(); textFormat = nullptr; }
dwFactory->CreateTextFormat(L"Consolas", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, currentFontSize, L"en-us", &textFormat);
lineHeight = currentFontSize * 1.25f;
if (textFormat) {
textFormat->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, lineHeight, lineHeight * 0.8f);
textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
}
IDWriteTextLayout* layout = nullptr;
if (SUCCEEDED(dwFactory->CreateTextLayout(L"0", 1, textFormat, 100.0f, 100.0f, &layout))) {
DWRITE_TEXT_METRICS m;
layout->GetMetrics(&m);
charWidth = m.width;
layout->Release();
}
if (textFormat) {
textFormat->SetIncrementalTabStop(charWidth * 4.0f);
}
updateGutterWidth();
updateScrollBars();
}
void destroyGraphics() {
if (hFileIcon) { DestroyIcon(hFileIcon); hFileIcon = NULL; }
if (dcompTarget) dcompTarget->Release();
if (dcompDevice) dcompDevice->Release();
if (targetBitmap) targetBitmap->Release();
if (swapChain) swapChain->Release();
if (rend) rend->Release();
if (popupTextFormat) popupTextFormat->Release();
if (helpTextFormat) helpTextFormat->Release();
if (dotStyle) dotStyle->Release();
if (roundJoinStyle) roundJoinStyle->Release();
if (textFormat) textFormat->Release();
if (dwFactory) dwFactory->Release();
if (d2dFactory) d2dFactory->Release();
}
void updateTitleBar() {
if (!hwnd) return;
std::wstring title;
if (isDirty) title = L"*";
if (currentFilePath.empty()) {
title += GetResString(IDS_UNTITLED);
}
else {
std::wstring fileName = currentFilePath;
size_t lastSlash = currentFilePath.find_last_of(L"\\/");
if (lastSlash != std::wstring::npos) {
fileName = currentFilePath.substr(lastSlash + 1);
}
title += fileName;
}
SetWindowTextW(hwnd, title.c_str());
}
void updateWindowIcon() {
if (!hwnd) return;
if (hFileIcon) {
DestroyIcon(hFileIcon);
hFileIcon = NULL;
}
HICON iconForTitleBar = hAppIcon;
if (!currentFilePath.empty()) {
SHFILEINFOW sfi = { 0 };
if (SHGetFileInfoW(currentFilePath.c_str(), 0, &sfi, sizeof(sfi), SHGFI_ICON | SHGFI_SMALLICON)) {
hFileIcon = sfi.hIcon;
iconForTitleBar = hFileIcon;
}
}
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)iconForTitleBar);
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hAppIcon);
}
void updateDirtyFlag() { bool newDirty = undo.isModified(); if (isDirty != newDirty) { isDirty = newDirty; updateTitleBar(); } }
void updateGutterWidth() {
if (suppressUI) return;
int totalLines = (int)lineStarts.size();
int digits = 1;
int tempLines = totalLines;
while (tempLines >= 10) {
tempLines /= 10;
digits++;
}
gutterWidth = (float)(digits * charWidth) + (charWidth * 1.0f);
}
void rebuildLineStarts() {
lineStarts.clear();
size_t totalLen = pt.length();
if (totalLen > 0) lineStarts.reserve(totalLen / 40 + 1);
lineStarts.push_back(0);
size_t globalOffset = 0;
size_t maxBytes = 0;
int maxBytesLineIdx = -1;
int currentLineIdx = 0;
for (const auto& p : pt.pieces) {
const char* buf = p.isOriginal ? (pt.origPtr + p.start) : (pt.addBuf.data() + p.start);
const char* ptr = buf;
const char* end = buf + p.len;
while (ptr < end) {
char c = *ptr;
if (c == '\n') {
size_t offsetInPiece = ptr - buf;
size_t nextLineStart = globalOffset + offsetInPiece + 1;
size_t currentLineLen = nextLineStart - lineStarts.back();
if (currentLineLen > maxBytes) {
maxBytes = currentLineLen;
maxBytesLineIdx = currentLineIdx;
}
lineStarts.push_back(nextLineStart);
ptr++;
currentLineIdx++;
}
else if (c == '\r') {
size_t offsetInPiece = ptr - buf;
size_t step = 1;
if (ptr + 1 < end && *(ptr + 1) == '\n') {
step = 2;
}
size_t nextLineStart = globalOffset + offsetInPiece + step;
size_t currentLineLen = nextLineStart - lineStarts.back();
if (currentLineLen > maxBytes) {
maxBytes = currentLineLen;
maxBytesLineIdx = currentLineIdx;
}
lineStarts.push_back(nextLineStart);
ptr += step;
currentLineIdx++;
}
else {
ptr++;
}
}
globalOffset += p.len;
}
size_t lastStart = lineStarts.back();
if (lastStart < totalLen) {
size_t lastLineLen = totalLen - lastStart;
if (lastLineLen > maxBytes) {
maxBytes = lastLineLen;
maxBytesLineIdx = currentLineIdx;
}
}
maxLineWidth = 100.0f;
if (maxBytesLineIdx >= 0 && dwFactory && textFormat) {
size_t start = lineStarts[maxBytesLineIdx];
size_t end = (maxBytesLineIdx + 1 < (int)lineStarts.size()) ? lineStarts[maxBytesLineIdx + 1] : pt.length();
size_t len = (end > start) ? (end - start) : 0;
if (len > 0) {
std::string lineStr = pt.getRange(start, len);
if (!lineStr.empty() && lineStr.back() == '\n') lineStr.pop_back();
if (!lineStr.empty() && lineStr.back() == '\r') lineStr.pop_back();
std::wstring wLine = UTF8ToW(lineStr);
IDWriteTextLayout* layout = nullptr;
HRESULT hr = dwFactory->CreateTextLayout(wLine.c_str(), (UINT32)wLine.size(), textFormat, 100000.0f, (FLOAT)lineHeight, &layout);
if (SUCCEEDED(hr) && layout) {
DWRITE_TEXT_METRICS metrics;
if (SUCCEEDED(layout->GetMetrics(&metrics))) {
maxLineWidth = metrics.widthIncludingTrailingWhitespace + charWidth * 2.0f + 50.0f;
}
layout->Release();
}
}
}
else {
maxLineWidth = maxBytes * charWidth + 100.0f;
}
updateGutterWidth();
updateScrollBars();
}
int getLineIdx(size_t pos) {
if (lineStarts.empty()) return 0;
auto it = std::upper_bound(lineStarts.begin(), lineStarts.end(), pos); int idx = (int)std::distance(lineStarts.begin(), it) - 1;
if (idx < 0) idx = 0; if (idx >= (int)lineStarts.size()) idx = (int)lineStarts.size() - 1; return idx;
}
float getXFromPos(size_t pos) {
int lineIdx = getLineIdx(pos); size_t start = lineStarts[lineIdx];
size_t end = (lineIdx + 1 < (int)lineStarts.size()) ? lineStarts[lineIdx + 1] : pt.length(); size_t len = (end > start) ? (end - start) : 0;
std::string lineStr = pt.getRange(start, len); std::wstring wLine = UTF8ToW(lineStr);
IDWriteTextLayout* layout = nullptr;
HRESULT hr = dwFactory->CreateTextLayout(wLine.c_str(), (UINT32)wLine.size(), textFormat, 10000000.0f, (FLOAT)lineHeight, &layout);
float x = 0;
if (SUCCEEDED(hr) && layout) {
size_t utf8Len = (pos >= start) ? (pos - start) : 0;
if (utf8Len > lineStr.size()) utf8Len = lineStr.size();
std::string subUtf8 = lineStr.substr(0, utf8Len);
std::wstring subUtf16 = UTF8ToW(subUtf8);
UINT32 u16Idx = (UINT32)subUtf16.size();
if (u16Idx > wLine.size()) u16Idx = (UINT32)wLine.size();
DWRITE_HIT_TEST_METRICS m; FLOAT px, py;
layout->HitTestTextPosition(u16Idx, FALSE, &px, &py, &m);
x = px;
layout->Release();
}
return x;
}
size_t getPosFromLineAndX(int lineIdx, float targetX) {
if (lineIdx < 0 || lineIdx >= (int)lineStarts.size()) return cursors.empty() ? 0 : cursors.back().head;
size_t start = lineStarts[lineIdx];
size_t end = (lineIdx + 1 < (int)lineStarts.size()) ? lineStarts[lineIdx + 1] : pt.length();
size_t len = (end > start) ? (end - start) : 0;
std::string lineStr = pt.getRange(start, len);
std::wstring wLine = UTF8ToW(lineStr);
IDWriteTextLayout* layout = nullptr;
HRESULT hr = dwFactory->CreateTextLayout(wLine.c_str(), (UINT32)wLine.size(), textFormat, 10000000.0f, (FLOAT)lineHeight, &layout);
size_t resultPos = start;
if (SUCCEEDED(hr) && layout) {
BOOL isTrailing, isInside;
DWRITE_HIT_TEST_METRICS m;
layout->HitTestPoint(targetX, 1.0f, &isTrailing, &isInside, &m);
size_t local = m.textPosition;
if (isTrailing) local += m.length;
size_t limit = wLine.size();
if (limit > 0 && wLine.back() == L'\n') {
limit--;
if (limit > 0 && wLine[limit - 1] == L'\r') limit--;
}
if (local > limit) local = limit;
std::wstring wSub = wLine.substr(0, local);
std::string sub = WToUTF8(wSub);
resultPos = start + sub.size();
layout->Release();
}
return resultPos;
}
void updateScrollBars() {
if (suppressUI) return;
if (!hwnd) return;
RECT rc; GetClientRect(hwnd, &rc);
float clientH = (rc.bottom - rc.top) / dpiScaleY;
float clientW = (rc.right - rc.left) / dpiScaleX - gutterWidth;
if (clientW < 0) clientW = 0;
int maxH = std::max(0, (int)(maxLineWidth - clientW + charWidth * 4.0f));
if (hScrollPos > maxH) hScrollPos = maxH;
if (hScrollPos < 0) hScrollPos = 0;
int linesVisible = (int)(clientH / lineHeight);
int maxV = std::max(0, (int)lineStarts.size() - 1);
if (vScrollPos > maxV) vScrollPos = maxV;
if (vScrollPos < 0) vScrollPos = 0;
}
void getCaretPoint(float& x, float& y) {
if (cursors.empty()) { x = 0; y = 0; return; }
size_t pos = cursors.back().head; int line = getLineIdx(pos); float docY = line * lineHeight; float localX = getXFromPos(pos);
x = (localX - hScrollPos + gutterWidth) * dpiScaleX; y = (docY - vScrollPos * lineHeight) * dpiScaleY;
}
void ensureCaretVisible() {
if (cursors.empty()) return;
Cursor& mainCursor = cursors.back();
RECT rc; GetClientRect(hwnd, &rc);
float clientH = (rc.bottom - rc.top) / dpiScaleY;
float clientW = (rc.right - rc.left) / dpiScaleX;
int linesVisible = (int)(clientH / lineHeight);
int caretLine = getLineIdx(mainCursor.head);
if (caretLine < vScrollPos) vScrollPos = caretLine;
else if (caretLine >= vScrollPos + linesVisible - 1) vScrollPos = caretLine - linesVisible + 2;
if (vScrollPos < 0) vScrollPos = 0;
float visibleTextW = clientW - gutterWidth;
if (visibleTextW < charWidth) visibleTextW = charWidth;
float caretX = getXFromPos(mainCursor.head);
float margin = charWidth * 2.0f;
if (caretX < hScrollPos + margin) {
hScrollPos = (int)(caretX - margin);
}
else if (caretX > hScrollPos + visibleTextW - margin) {
hScrollPos = (int)(caretX - visibleTextW + margin);
}
float requiredWidth = hScrollPos + visibleTextW + margin;
if (caretX + margin * 4.0f > requiredWidth) requiredWidth = caretX + margin * 4.0f;
if (requiredWidth > maxLineWidth) {
maxLineWidth = requiredWidth;
}
if (hScrollPos < 0) hScrollPos = 0;
updateScrollBars();
InvalidateRect(hwnd, NULL, FALSE);
}
std::string buildVisibleText(int numLines) {
if (lineStarts.empty()) return "";
size_t startOffset = (vScrollPos < (int)lineStarts.size()) ? lineStarts[vScrollPos] : lineStarts.back();
size_t endOffset = pt.length(); int endLineIdx = vScrollPos + numLines; if (endLineIdx < (int)lineStarts.size()) endOffset = lineStarts[endLineIdx];
return pt.getRange(startOffset, (endOffset > startOffset) ? (endOffset - startOffset) : 0);
}
size_t getDocPosFromPoint(int x, int y) {
float dipX = x / dpiScaleX; float dipY = y / dpiScaleY; if (dipX < gutterWidth) dipX = gutterWidth;
float virtualX = dipX - gutterWidth + hScrollPos; float virtualY = dipY;
RECT rc; GetClientRect(hwnd, &rc); float clientH = (rc.bottom - rc.top) / dpiScaleY; float clientW = (rc.right - rc.left) / dpiScaleX - gutterWidth;
int linesVisible = (int)(clientH / lineHeight) + 2; std::string text = buildVisibleText(linesVisible); std::wstring wtext = UTF8ToW(text);
float layoutWidth = maxLineWidth + clientW;
IDWriteTextLayout* layout = nullptr; HRESULT hr = dwFactory->CreateTextLayout(wtext.c_str(), (UINT32)wtext.size(), textFormat, layoutWidth, clientH, &layout);
size_t resultPos = 0; size_t visibleStartOffset = (vScrollPos < (int)lineStarts.size()) ? lineStarts[vScrollPos] : pt.length();
if (SUCCEEDED(hr) && layout) {
BOOL isTrailing, isInside; DWRITE_HIT_TEST_METRICS metrics; layout->HitTestPoint(virtualX, virtualY, &isTrailing, &isInside, &metrics);
UINT32 utf16Index = metrics.textPosition; if (isTrailing) utf16Index += metrics.length;
if (utf16Index > wtext.size()) utf16Index = (UINT32)wtext.size(); std::wstring wsub = wtext.substr(0, utf16Index); std::string sub = WToUTF8(wsub);
resultPos = visibleStartOffset + sub.size(); layout->Release();
}
if (resultPos > pt.length()) resultPos = pt.length(); return resultPos;
}
bool isWordChar(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_' ||
(unsigned char)c >= 0x80;
}
void mergeCursors() {
if (cursors.empty()) return;
std::sort(cursors.begin(), cursors.end(), [](const Cursor& a, const Cursor& b) { return a.head < b.head; });
std::vector<Cursor> merged; merged.push_back(cursors[0]);
for (size_t i = 1; i < cursors.size(); ++i) {
Cursor& prev = merged.back(); Cursor& curr = cursors[i];
if (curr.start() <= prev.end()) { size_t newStart = std::min(prev.start(), curr.start()); size_t newEnd = std::max(prev.end(), curr.end()); bool prevForward = prev.head >= prev.anchor; prev.anchor = prevForward ? newStart : newEnd; prev.head = prevForward ? newEnd : newStart; }
else { merged.push_back(curr); }
}
cursors = merged;
}
void selectWordAt(size_t pos) {
if (pos >= pt.length()) { cursors.clear(); cursors.push_back({ pos, pos, getXFromPos(pos) }); return; }
char c = pt.charAt(pos);
if (c == '\r') {
if (pos + 1 < pt.length() && pt.charAt(pos + 1) == '\n') {
cursors.clear();
cursors.push_back({ pos + 2, pos, getXFromPos(pos + 2) });