-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSource.cpp
More file actions
2027 lines (2017 loc) · 396 KB
/
Copy pathSource.cpp
File metadata and controls
2027 lines (2017 loc) · 396 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 <initguid.h>
#include <d2d1effects.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, "dxguid.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.23";
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 void UTF8ToW(const std::string& s, std::wstring& out) {
out.clear();
if (s.empty()) return;
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), NULL, 0);
if (n <= 0) return;
out.resize(n);
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), &out[0], n);
}
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; getRange(pos, count, out); return out;
}
void getRange(size_t pos, size_t count, std::string& out) const {
out.clear(); if (count == 0) return;
out.reserve(count); 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;
}
}
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;
std::vector<char> heapBuffer; bool isMapped = false;
static const size_t THRESHOLD = 50 * 1024 * 1024; // 50MB
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)) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; return false; }
size = (size_t)li.QuadPart;
if (size == 0) { ptr = nullptr; CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; return true; }
if (size >= THRESHOLD) {
hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (!hMap) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; return false; }
ptr = (const char*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0); isMapped = true; return !!ptr;
}
else {
heapBuffer.resize(size); DWORD bytesRead = 0;
if (ReadFile(hFile, heapBuffer.data(), (DWORD)size, &bytesRead, NULL) && bytesRead == size) {
ptr = heapBuffer.data(); isMapped = false; CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; return true;
}
CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; return false;
}
}
void close() {
if (isMapped && ptr) { UnmapViewOfFile(ptr); ptr = nullptr; }
if (hMap) { CloseHandle(hMap); hMap = NULL; }
if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; }
heapBuffer.clear(); ptr = nullptr; size = 0; isMapped = false;
}
~MappedFile() { close(); }
};
#include <unordered_set>
#include <unordered_map>
#include <cwctype>
struct SyntaxDef {
std::unordered_set<std::string> keywords;
std::unordered_set<std::string> literals;
std::string commentLine;
std::string commentBlockStart;
std::string commentBlockEnd;
std::vector<std::pair<std::regex, D2D1::ColorF>> regexes;
};
class CustomTextRenderer : public IDWriteTextRenderer {
public:
ID2D1DeviceContext* rend;
ID2D1SolidColorBrush* defaultBrush;
CustomTextRenderer(ID2D1DeviceContext* r, ID2D1SolidColorBrush* b) : rend(r), defaultBrush(b) {}
IFACEMETHOD(DrawGlyphRun)(void*, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_GLYPH_RUN_DESCRIPTION const*, IUnknown* clientDrawingEffect) override {
ID2D1SolidColorBrush* brush = defaultBrush;
if (clientDrawingEffect) clientDrawingEffect->QueryInterface(__uuidof(ID2D1SolidColorBrush), (void**)&brush);
rend->DrawGlyphRun(D2D1::Point2F(baselineOriginX, baselineOriginY), glyphRun, brush, measuringMode);
if (clientDrawingEffect && brush != defaultBrush) brush->Release();
return S_OK;
}
IFACEMETHOD(DrawUnderline)(void*, FLOAT, FLOAT, DWRITE_UNDERLINE const*, IUnknown*) override { return E_NOTIMPL; }
IFACEMETHOD(DrawStrikethrough)(void*, FLOAT, FLOAT, DWRITE_STRIKETHROUGH const*, IUnknown*) override { return E_NOTIMPL; }
IFACEMETHOD(DrawInlineObject)(void*, FLOAT, FLOAT, IDWriteInlineObject*, BOOL, BOOL, IUnknown*) override { return E_NOTIMPL; }
IFACEMETHOD(IsPixelSnappingDisabled)(void*, BOOL* disabled) override { *disabled = FALSE; return S_OK; }
IFACEMETHOD(GetCurrentTransform)(void*, DWRITE_MATRIX* m) override { rend->GetTransform((D2D1_MATRIX_3X2_F*)m); return S_OK; }
IFACEMETHOD(GetPixelsPerDip)(void*, FLOAT* pixelsPerDip) override { *pixelsPerDip = 1.0f; return S_OK; }
IFACEMETHODIMP_(ULONG) AddRef() { return 1; }
IFACEMETHODIMP_(ULONG) Release() { return 1; }
IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv) {
if (riid == __uuidof(IDWriteTextRenderer) || riid == __uuidof(IDWritePixelSnapping) || riid == __uuidof(IUnknown)) { *ppv = this; return S_OK; }
*ppv = NULL; return E_NOINTERFACE;
}
};
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; bool isAutoScrolling = false;
float rectAnchorX = 0; int rectAnchorLine = 0; float rectHeadX = 0; int rectHeadLine = 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;
bool wordWrapEnabled = false;
MiuEncoding currentEncoding = ENC_UTF8_NOBOM; UINT currentCodePage = CP_UTF8; std::string convertedBuffer; std::string newlineStr = "\r\n";
SyntaxDef currentSyntax;
ID2D1SolidColorBrush* keywordBrush = nullptr;
ID2D1SolidColorBrush* literalBrush = nullptr;
ID2D1SolidColorBrush* commentBrush = nullptr;
ID2D1SolidColorBrush* stringBrush = nullptr;
std::vector<ID2D1SolidColorBrush*> regexBrushes;
FILETIME lastWriteTime = { 0, 0 }; bool isCheckingModification = false;
void updateFileTime() {
if (currentFilePath.empty()) { lastWriteTime = { 0, 0 }; return; }
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(currentFilePath.c_str(), GetFileExInfoStandard, &fad)) { lastWriteTime = fad.ftLastWriteTime; }
else { lastWriteTime = { 0, 0 }; }
}
void checkFileModification() {
if (currentFilePath.empty() || isCheckingModification) return;
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(currentFilePath.c_str(), GetFileExInfoStandard, &fad)) {
if (CompareFileTime(&lastWriteTime, &fad.ftLastWriteTime) < 0) {
isCheckingModification = true;
std::wstring msg = GetResString(IDS_FILE_CHANGED_EXT);
if (isDirty) msg += GetResString(IDS_FILE_CHANGED_WARN);
int r = ShowTaskDialog(GetResString(IDS_FILE_CHANGED_TITLE).c_str(), msg.c_str(), currentFilePath.c_str(), TDCBF_YES_BUTTON | TDCBF_NO_BUTTON, TD_INFORMATION_ICON);
if (r == IDYES) openFileFromPath(currentFilePath);
else lastWriteTime = fad.ftLastWriteTime;
isCheckingModification = false;
}
}
}
void loadSyntaxForExtension(const std::wstring& ext) {
static bool initialized = false;
static std::unordered_map<std::wstring, std::string> syntaxStrMap;
if (!initialized) {
initialized = true;
syntaxStrMap[L"cpp"] = syntaxStrMap[L"c"] = syntaxStrMap[L"h"] = syntaxStrMap[L"hpp"] = R"([cpp]
keyword: int float double return if else for while break class struct static virtual void bool const auto namespace using template typename public private protected new delete goto unsigned char short long typedef sizeof switch case default constexpr noexcept inline explicit friend mutable catch try throw operator decltype alignas alignof static_cast dynamic_cast reinterpret_cast const_cast typeid union enum final override thread_local DWORD HWND HRESULT HANDLE HINSTANCE HICON HCURSOR HBRUSH HKEY HDC HGLRC LRESULT WPARAM LPARAM WNDCLASS WNDCLASSEX MSG PAINTSTRUCT RECT FILETIME SYSTEMTIME WORD BYTE UINT ULONG LONG INT BOOL BOOLEAN TCHAR WCHAR LPSTR LPCSTR LPWSTR LPCWSTR LPTSTR LPCTSTR LPVOID PVOID std vector string wstring map set unordered_map unordered_set list deque stringstream wstringstream regex sregex_iterator
literal: true false nullptr TRUE FALSE NULL INFINITE INVALID_HANDLE_VALUE
comment_line: //
comment_block: /* */
regex: #[ \t]*include[ \t]*[<"][^>"]+[>"]
regex_color: 0.6 0.4 0.6 1.0
regex: #[ \t]*[a-zA-Z0-9_]+
regex_color: 0.6 0.4 0.6 1.0
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?([fFlLuU]*))\b
regex_color: 0.4 0.7 0.6 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"cs"] = R"([cs]
keyword: abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while async await var yield nameof record init get set
literal: true false null
comment_line: //
comment_block: /* */
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?([fFlLmUdD]*))\b
regex_color: 0.4 0.7 0.6 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"py"] = R"([python]
keyword: and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass print raise return try while with yield async await match case type
literal: True False None
comment_line: #
comment_block: """ """
regex: \b(0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?(j)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"js"] = syntaxStrMap[L"ts"] = syntaxStrMap[L"jsx"] = syntaxStrMap[L"tsx"] = R"([js]
keyword: break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with yield let static enum implements package protected interface private public async await type namespace declare module as any unknown never boolean number string symbol get set require exports
literal: true false null undefined NaN Infinity
comment_line: //
comment_block: /* */
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"json"] = R"([json]
literal: true false null
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"html"] = syntaxStrMap[L"htm"] = syntaxStrMap[L"xml"] = R"([html]
comment_block: <!-- -->
regex: </?[a-zA-Z0-9\-:]+>?
regex_color: 0.3 0.6 0.8 1.0
regex: \b[a-zA-Z0-9\-:]+(?=\s*=)
regex_color: 0.8 0.5 0.3 1.0
regex: &[#a-zA-Z0-9]+;
regex_color: 0.6 0.4 0.7 1.0
)";
syntaxStrMap[L"css"] = R"([css]
comment_block: /* */
regex: \b[a-zA-Z\-]+(?=\s*:)
regex_color: 0.3 0.6 0.8 1.0
regex: \B#[0-9a-fA-F]{3,6}\b
regex_color: 0.6 0.4 0.7 1.0
regex: \b(px|em|rem|vh|vw|%)\b
regex_color: 0.8 0.5 0.3 1.0
regex: (\.|#|:)[a-zA-Z_\-]+
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"md"] = syntaxStrMap[L"markdown"] = R"([markdown]
regex: ^[ \t]*#{1,6}[ \t]+.*
regex_color: 0.3 0.7 0.9 1.0
regex: (\*\*|__)[^\*\_]+(\*\*|__)
regex_color: 0.9 0.5 0.3 1.0
regex: `[^`]+`
regex_color: 0.5 0.7 0.5 1.0
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
)";
syntaxStrMap[L"rs"] = R"([rust]
keyword: as break const continue crate else enum extern fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait type unsafe use where while async await dyn abstract become box do final macro override priv typeof unsized virtual yield
literal: true false Option Result Some None Ok Err
comment_line: //
comment_block: /* */
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?([a-zA-Z0-9_]*))\b
regex_color: 0.4 0.7 0.6 1.0
regex: #[ \t]*\[.*?\]
regex_color: 0.6 0.4 0.7 1.0
regex: \b[a-zA-Z_][a-zA-Z0-9_]*!
regex_color: 0.3 0.6 0.8 1.0
)";
syntaxStrMap[L"go"] = R"([go]
keyword: break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var
literal: true false iota nil make new len cap append close delete panic recover
comment_line: //
comment_block: /* */
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"java"] = R"([java]
keyword: abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while var yield record sealed permits non-sealed
literal: true false null
comment_line: //
comment_block: /* */
regex: \b(0x[0-9a-fA-F]+|[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?([fFlLdD]*))\b
regex_color: 0.4 0.7 0.6 1.0
regex: @[a-zA-Z_][a-zA-Z0-9_]*
regex_color: 0.6 0.4 0.7 1.0
)";
syntaxStrMap[L"ps1"] = R"([powershell]
keyword: begin break catch continue data do dynamicparam else elseif end exit filter finally for foreach from function if in inlineScript parallel param process return sequence switch throw trap try until while workflow
literal: $true $false $null
comment_line: #
comment_block: <# #>
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: \$[a-zA-Z_][a-zA-Z0-9_]*
regex_color: 0.8 0.5 0.3 1.0
regex: -[a-zA-Z_][a-zA-Z0-9_]*
regex_color: 0.4 0.7 0.9 1.0
)";
syntaxStrMap[L"bat"] = syntaxStrMap[L"cmd"] = R"([batch]
keyword: call cd chdir choice cls color copy date del dir echo endlocal erase exit find findstr for goto if md mkdir move path pause popd prompt pushd rd rem ren rename rmdir set setlocal shift start time title type ver verify vol CALL CD CHDIR CHOICE CLS COLOR COPY DATE DEL DIR ECHO ENDLOCAL ERASE EXIT FIND FINDSTR FOR GOTO IF MD MKDIR MOVE PATH PAUSE POPD PROMPT PUSHD RD REM REN RENAME RMDIR SET SETLOCAL SHIFT START TIME TITLE TYPE VER VERIFY VOL
regex: ^[ \t]*([rR][eE][mM]|::).*
regex_color: 0.38 0.62 0.38 1.0
regex: %[a-zA-Z0-9_]+%
regex_color: 0.8 0.5 0.3 1.0
regex: ^[ \t]*:[a-zA-Z0-9_]+
regex_color: 0.6 0.4 0.7 1.0
)";
syntaxStrMap[L"sh"] = syntaxStrMap[L"bash"] = R"([bash]
keyword: if then else elif fi case esac for select while until do done in function time coproc source alias export read local
literal: true false
comment_line: #
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: \$[a-zA-Z_][a-zA-Z0-9_]*
regex_color: 0.8 0.5 0.3 1.0
regex: \$\{[^\}]+\}
regex_color: 0.8 0.5 0.3 1.0
)";
syntaxStrMap[L"sql"] = R"([sql]
comment_line: --
comment_block: /* */
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: \b(SELECT|INSERT|UPDATE|DELETE|FROM|WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|ON|GROUP|BY|ORDER|HAVING|LIMIT|OFFSET|AS|IN|AND|OR|NOT|IS|NULL|CREATE|ALTER|DROP|TABLE|INDEX|VIEW|PRIMARY|KEY|FOREIGN|REFERENCES|DEFAULT|UNIQUE)\b
regex_color: 0.3 0.6 0.8 1.0
regex: \b(select|insert|update|delete|from|where|join|left|right|inner|outer|on|group|by|order|having|limit|offset|as|in|and|or|not|is|null|create|alter|drop|table|index|view|primary|key|foreign|references|default|unique)\b
regex_color: 0.3 0.6 0.8 1.0
)";
syntaxStrMap[L"php"] = R"([php]
keyword: echo print if else elseif for foreach while do switch case break continue return include require function class public private protected static try catch throw new extends implements trait namespace use yield global
literal: true false null TRUE FALSE NULL
comment_line: //
comment_block: /* */
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
regex: \$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
regex_color: 0.8 0.5 0.3 1.0
)";
syntaxStrMap[L"rb"] = syntaxStrMap[L"ruby"] = R"([ruby]
keyword: def end class module if unless else elsif case when while until for do yield return break next redo retry rescue ensure super alias undef in include require
literal: true false nil self
comment_line: #
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"swift"] = R"([swift]
keyword: func var let class struct enum protocol extension init deinit return if else switch case for in while do catch throw try await async guard defer fileprivate private open public internal
literal: true false nil
comment_line: //
comment_block: /* */
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"kt"] = syntaxStrMap[L"kotlin"] = R"([kotlin]
keyword: fun val var class interface object package import return if else when for while do break continue try catch finally throw in is as typealias
literal: true false null
comment_line: //
comment_block: /* */
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?([fFlL]*))\b
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"lua"] = R"([lua]
keyword: and break do else elseif end false for function if in local nil not or repeat return then true until while
literal: true false nil
comment_line: --
comment_block: --[[ ]]
regex: \b([0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\b
regex_color: 0.4 0.7 0.6 1.0
)";
syntaxStrMap[L"yml"] = syntaxStrMap[L"yaml"] = R"([yaml]
comment_line: #
regex: ^[ \t]*[a-zA-Z0-9_\-]+:
regex_color: 0.3 0.6 0.8 1.0
regex: \b(true|false|null)\b
regex_color: 0.8 0.4 0.2 1.0
)";
syntaxStrMap[L"tex"] = syntaxStrMap[L"latex"] = R"([latex]
comment_line: %
regex: \\[a-zA-Z]+
regex_color: 0.3 0.6 0.8 1.0
regex: \{.*?\}
regex_color: 0.8 0.5 0.3 1.0
regex: \$.*?\$
regex_color: 0.6 0.4 0.7 1.0
)";
syntaxStrMap[L""] = R"([default]
regex: (https?|ftp)://[^\s/$.?#].[^\s]*
regex_color: 0.2 0.6 0.8 1.0
regex: \b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
regex_color: 0.8 0.4 0.2 1.0
)";
}
std::wstring lowerExt = ext;
for (auto& c : lowerExt) c = std::towlower(c);
std::string targetSyntax = syntaxStrMap[L""];
if (syntaxStrMap.count(lowerExt)) {
targetSyntax = syntaxStrMap[lowerExt];
}
currentSyntax = SyntaxDef();
std::stringstream ss(targetSyntax);
std::string line;
std::string lastRegex;
while (std::getline(ss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.find("keyword: ") == 0) {
std::stringstream ws(line.substr(9)); std::string w;
while (ws >> w) currentSyntax.keywords.insert(w);
}
if (line.find("literal: ") == 0) {
std::stringstream ws(line.substr(9)); std::string w;
while (ws >> w) currentSyntax.literals.insert(w);
}
if (line.find("comment_line: ") == 0) currentSyntax.commentLine = line.substr(14);
if (line.find("comment_block: ") == 0) {
std::stringstream ws(line.substr(15));
ws >> currentSyntax.commentBlockStart >> currentSyntax.commentBlockEnd;
}
if (line.find("regex: ") == 0) lastRegex = line.substr(7);
if (line.find("regex_color: ") == 0 && !lastRegex.empty()) {
float r, g, b, a;
if (sscanf_s(line.substr(13).c_str(), "%f %f %f %f", &r, &g, &b, &a) == 4) {
currentSyntax.regexes.push_back({ std::regex(lastRegex, std::regex_constants::optimize), D2D1::ColorF(r, g, b, a) });
}
lastRegex = "";
}
}
}
bool checkInBlockComment(size_t visibleStart) {
if (currentSyntax.commentBlockStart.empty() || currentSyntax.commentBlockEnd.empty()) return false;
if (visibleStart == 0) return false;
size_t maxSearch = std::min((size_t)50000, visibleStart);
std::string preText = pt.getRange(visibleStart - maxSearch, maxSearch);
size_t lastOpen = preText.rfind(currentSyntax.commentBlockStart);
size_t lastClose = preText.rfind(currentSyntax.commentBlockEnd);
if (lastOpen != std::string::npos) {
if (lastClose == std::string::npos || lastOpen > lastClose) {
size_t lastNewline = preText.rfind('\n', lastOpen);
size_t startSearchLine = (lastNewline == std::string::npos) ? 0 : lastNewline + 1;
if (!currentSyntax.commentLine.empty()) {
size_t lineCommentPos = preText.find(currentSyntax.commentLine, startSearchLine);
if (lineCommentPos != std::string::npos && lineCommentPos < lastOpen) {
return false;
}
}
bool insideString = false;
for (size_t k = startSearchLine; k < lastOpen; ++k) {
if (preText[k] == '"' || preText[k] == '\'') {
if (k > 0 && preText[k - 1] == '\\') continue;
insideString = !insideString;
}
}
if (insideString) return false;
return true;
}
}
return false;
}
void applySyntaxHighlighting(IDWriteTextLayout* layout, const std::string& visibleText, size_t visibleStartOffset) {
if (visibleText.empty()) return;
bool inBlockComment = checkInBlockComment(visibleStartOffset);
auto setEffect = [&](size_t utf8Start, size_t utf8Len, ID2D1SolidColorBrush* brush) {
if (utf8Len == 0 || !brush) return;
size_t wStart = utf8OffsetToUtf16Count(visibleText, utf8Start);
size_t wLen = utf8OffsetToUtf16Count(visibleText, utf8Start + utf8Len) - wStart;
DWRITE_TEXT_RANGE range = { (UINT32)wStart, (UINT32)wLen };
layout->SetDrawingEffect(brush, range);
};
for (size_t i = 0; i < currentSyntax.regexes.size(); ++i) {
if (i >= regexBrushes.size()) break;
std::sregex_iterator words_begin(visibleText.begin(), visibleText.end(), currentSyntax.regexes[i].first);
std::sregex_iterator words_end;
for (auto it = words_begin; it != words_end; ++it) {
setEffect(it->position(), it->length(), regexBrushes[i]);
}
}
size_t i = 0;
size_t len = visibleText.length();
while (i < len) {
if (inBlockComment) {
size_t startStr = i;
size_t endComment = visibleText.find(currentSyntax.commentBlockEnd, i);
if (endComment != std::string::npos) {
i = endComment + currentSyntax.commentBlockEnd.length();
inBlockComment = false;
}
else {
i = len;
}
setEffect(startStr, i - startStr, commentBrush);
}
else {
if (!currentSyntax.commentBlockStart.empty() && visibleText.compare(i, currentSyntax.commentBlockStart.length(), currentSyntax.commentBlockStart) == 0) {
inBlockComment = true;
continue;
}
if (!currentSyntax.commentLine.empty() && visibleText.compare(i, currentSyntax.commentLine.length(), currentSyntax.commentLine) == 0) {
size_t startStr = i;
size_t eol = visibleText.find('\n', i);
if (eol == std::string::npos) eol = len;
i = eol;
setEffect(startStr, i - startStr, commentBrush);
continue;
}
if (visibleText[i] == '"' || visibleText[i] == '\'') {
char quote = visibleText[i];
size_t startStr = i;
i++;
while (i < len) {
if (visibleText[i] == '\\' && i + 1 < len) {
i += 2;
}
else if (visibleText[i] == quote) {
i++;
break;
}
else if (visibleText[i] == '\n') {
break;
}
else {
i++;
}
}
setEffect(startStr, i - startStr, stringBrush);
continue;
}
if (isWordChar(visibleText[i])) {
size_t startStr = i;
while (i < len && isWordChar(visibleText[i])) i++;
std::string word = visibleText.substr(startStr, i - startStr);
if (currentSyntax.keywords.count(word)) setEffect(startStr, i - startStr, keywordBrush);
else if (currentSyntax.literals.count(word)) setEffect(startStr, i - startStr, literalBrush);
continue;
}
i++;
}
}
}
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 (keywordBrush) { keywordBrush->Release(); keywordBrush = nullptr; }
if (literalBrush) { literalBrush->Release(); literalBrush = nullptr; }
if (commentBrush) { commentBrush->Release(); commentBrush = nullptr; }
if (stringBrush) { stringBrush->Release(); stringBrush = nullptr; }
for (auto b : regexBrushes) b->Release();
regexBrushes.clear();
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);
if (rend) {
rend->CreateSolidColorBrush(D2D1::ColorF(0.33f, 0.61f, 0.83f), &keywordBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.85f, 0.43f, 0.43f), &literalBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.38f, 0.62f, 0.38f), &commentBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.80f, 0.56f, 0.35f), &stringBrush);
for (auto& r : currentSyntax.regexes) {
ID2D1SolidColorBrush* b = nullptr;
rend->CreateSolidColorBrush(r.second, &b);
regexBrushes.push_back(b);
}
}
}
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);
if (rend) {
rend->CreateSolidColorBrush(D2D1::ColorF(0.0f, 0.0f, 1.0f), &keywordBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.0f, 0.0f), &literalBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.0f, 0.5f, 0.0f), &commentBrush);
rend->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.2f, 0.0f), &stringBrush);
for (auto& r : currentSyntax.regexes) {
ID2D1SolidColorBrush* b = nullptr;
rend->CreateSolidColorBrush(r.second, &b);
regexBrushes.push_back(b);
}
}
}
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 || 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));
loadSyntaxForExtension(L"");
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 (keywordBrush) { keywordBrush->Release(); keywordBrush = nullptr; }
if (literalBrush) { literalBrush->Release(); literalBrush = nullptr; }
if (commentBrush) { commentBrush->Release(); commentBrush = nullptr; }
if (stringBrush) { stringBrush->Release(); stringBrush = nullptr; }
for (auto b : regexBrushes) b->Release();
regexBrushes.clear();
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;
RECT rc; GetClientRect(hwnd, &rc); float clientW = (rc.right - rc.left) / dpiScaleX - gutterWidth; if (clientW < 0) clientW = 0;
float layoutWidth = wordWrapEnabled ? clientW : 10000000.0f;
HRESULT hr = dwFactory->CreateTextLayout(wLine.c_str(), (UINT32)wLine.size(), textFormat, layoutWidth, (FLOAT)lineHeight * 100.0f, &layout); float x = 0;
if (SUCCEEDED(hr) && layout) {
if (wordWrapEnabled) layout->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP); else layout->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
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;
RECT rc; GetClientRect(hwnd, &rc); float clientW = (rc.right - rc.left) / dpiScaleX - gutterWidth; if (clientW < 0) clientW = 0;
float layoutWidth = wordWrapEnabled ? clientW : 10000000.0f;
HRESULT hr = dwFactory->CreateTextLayout(wLine.c_str(), (UINT32)wLine.size(), textFormat, layoutWidth, (FLOAT)lineHeight * 100.0f, &layout); size_t resultPos = start;
if (SUCCEEDED(hr) && layout) {
if (wordWrapEnabled) layout->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP); else layout->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
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 || !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 = wordWrapEnabled ? 0 : std::max(0, (int)(maxLineWidth - clientW + charWidth * 4.0f)); if (hScrollPos > maxH) hScrollPos = maxH; if (hScrollPos < 0) hScrollPos = 0;
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 (vScrollPos < 0) vScrollPos = 0;
if (!wordWrapEnabled) {
if (caretLine < vScrollPos) vScrollPos = caretLine; else if (caretLine >= vScrollPos + linesVisible - 1) vScrollPos = caretLine - linesVisible + 2;
}
else {
if (caretLine < vScrollPos) {
vScrollPos = caretLine;
}
else {
int searchStartLine = std::max(vScrollPos, caretLine - linesVisible);
if (searchStartLine > vScrollPos) vScrollPos = searchStartLine;
size_t startPos = lineStarts[vScrollPos]; size_t endLine = caretLine + 1; if (endLine > lineStarts.size()) endLine = lineStarts.size();
size_t endPos = (endLine < lineStarts.size()) ? lineStarts[endLine] : pt.length();
if (endPos > startPos) {
std::string chunk; pt.getRange(startPos, endPos - startPos, chunk); std::wstring wchunk; UTF8ToW(chunk, wchunk);
IDWriteTextLayout* layout = nullptr; float w = clientW - gutterWidth; if (w < 0) w = 0;
if (SUCCEEDED(dwFactory->CreateTextLayout(wchunk.c_str(), (UINT32)wchunk.size(), textFormat, w, 1000000.0f, &layout))) {
layout->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
size_t relHead = mainCursor.head - startPos; UINT32 u16Head = (UINT32)utf8OffsetToUtf16Count(chunk, relHead);
DWRITE_HIT_TEST_METRICS m; FLOAT px, py; layout->HitTestTextPosition(u16Head, FALSE, &px, &py, &m);
float bottomMargin = lineHeight * 1.5f;