/
ctexteditor.cpp
2989 lines (2744 loc) · 90.2 KB
/
ctexteditor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "ccolor.h"
#include "cdrawcontext.h"
#include "cdropsource.h"
#include "cframe.h"
#include "controls/cscrollbar.h"
#include "cscrollview.h"
#include "ctexteditor.h"
#include "cgraphicspath.h"
#include "events.h"
#include "iviewlistener.h"
#include "cvstguitimer.h"
#include "finally.h"
#include "platform/iplatformfont.h"
#include "platform/iplatformframe.h"
#include "platform/platformfactory.h"
#include "controls/cbuttons.h"
#include "controls/ctextedit.h"
#include "animation/timingfunctions.h"
#include "animation/animations.h"
#include <optional>
#include <codecvt>
#include <locale>
#include <string>
#include <bitset>
#include <cwctype>
//------------------------------------------------------------------------
namespace VSTGUI {
namespace TextEditor {
using CharT = char16_t;
#define STB_TEXTEDIT_CHARTYPE CharT
#define STB_TEXTEDIT_POSITIONTYPE int32_t
#define STB_TEXTEDIT_STRING const TextEditorView
#define STB_TEXTEDIT_KEYTYPE uint32_t
#define STB_TEXTEDIT_UNDOSTATECOUNT 0
#define STB_TEXTEDIT_UNDOCHARCOUNT 0
#include "platform/common/stb_textedit.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4996)
#endif
using StringConvert = std::wstring_convert<std::codecvt_utf8_utf16<CharT>, CharT>;
//------------------------------------------------------------------------
inline std::u16string convert (const char* text, size_t numChars)
{
return StringConvert {}.from_bytes (text, text + numChars);
}
//------------------------------------------------------------------------
inline std::u16string convert (const std::string& str) { return StringConvert {}.from_bytes (str); }
//------------------------------------------------------------------------
inline std::string convert (const char16_t* text, size_t numChars)
{
return StringConvert {}.to_bytes (text, text + numChars);
}
//------------------------------------------------------------------------
inline std::string convert (const std::u16string& str) { return StringConvert {}.to_bytes (str); }
#ifdef __clang__
#pragma clang diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif
//------------------------------------------------------------------------
struct Range
{
size_t start {0};
size_t length {0};
explicit operator bool () const { return length > 0; }
size_t end () const { return start + length; }
};
//------------------------------------------------------------------------
bool operator== (const Range& r1, const Range& r2)
{
return r1.start == r2.start && r1.length == r2.length;
}
//------------------------------------------------------------------------
bool operator!= (const Range& r1, const Range& r2)
{
return r1.start != r2.start || r1.length != r2.length;
}
//------------------------------------------------------------------------
inline Range makeRange (size_t start, size_t end)
{
if (start > end)
std::swap (start, end);
return Range {static_cast<size_t> (start), static_cast<size_t> (end - start)};
}
//------------------------------------------------------------------------
inline Range makeRange (const STB_TexteditState& state)
{
return makeRange (state.select_start, state.select_end);
}
//------------------------------------------------------------------------
inline void replaceTabs (std::string& str, uint32_t tabWidth)
{
if (tabWidth < 1)
return;
std::string replaceStr;
while (--tabWidth)
replaceStr += ' ';
std::string::size_type pos = std::string::npos;
while ((pos = str.find_first_of ('\t')) != std::string::npos)
{
str[pos] = ' ';
str.replace (pos, 1, " ");
str.insert (pos, replaceStr);
}
}
using String = std::u16string;
using StringView = std::u16string_view;
//------------------------------------------------------------------------
struct Line
{
Range range;
UTF8String text;
CCoord width {};
};
using Lines = std::vector<Line>;
//------------------------------------------------------------------------
struct TextModel
{
String text;
Lines lines;
};
//------------------------------------------------------------------------
struct NewLineProcessor
{
static void update (Lines& lines, StringView text, size_t startRow);
};
struct LineNumberView;
struct FindPanelController;
static constexpr CPoint MouseOutsidePos = {std::numeric_limits<CCoord>::max (),
std::numeric_limits<CCoord>::max ()};
//------------------------------------------------------------------------
struct Key
{
char16_t character;
VirtualKey virt;
Modifiers modifiers;
bool operator== (const KeyboardEvent& event) const
{
return event.character == character && event.virt == virt && event.modifiers == modifiers;
}
};
using CommandKeyArray = std::array<Key, static_cast<size_t> (ITextEditor::Command::TakeFocus) + 1>;
//------------------------------------------------------------------------
struct TextEditorView : public CView,
public ITextEditor,
public TextEditorColorization::IEditorExt,
public IFocusDrawing,
public ViewEventListenerAdapter
{
TextEditorView (ITextEditorController* controller);
void beforeDelete () override;
void drawRect (CDrawContext* pContext, const CRect& dirtyRect) override;
bool attached (CView* parent) override;
bool removed (CView* parent) override;
void parentSizeChanged () override;
void looseFocus () override;
void takeFocus () override;
void onKeyboardEvent (KeyboardEvent& event) override;
void onMouseDownEvent (MouseDownEvent& event) override;
void onMouseMoveEvent (MouseMoveEvent& event) override;
void onMouseUpEvent (MouseUpEvent& event) override;
void onMouseCancelEvent (MouseCancelEvent& event) override;
void onMouseEnterEvent (MouseEnterEvent& event) override;
void onMouseExitEvent (MouseExitEvent& event) override;
void viewOnEvent (CView* view, Event& event) override;
int32_t deleteChars (size_t pos, size_t num) const;
int32_t insertChars (size_t pos, const CharT* text, size_t num) const;
void layout (StbTexteditRow* row, size_t start_i) const;
float getCharWidth (size_t row, size_t pos) const;
CharT getChar (int32_t pos) const;
int32_t getLength () const;
size_t moveToWordPrevious (size_t pos) const;
size_t moveToWordNext (size_t pos) const;
// STB
static int32_t deleteChars (const TextEditorView* self, size_t pos, size_t num)
{
return self->deleteChars (pos, num);
}
static int32_t insertChars (const TextEditorView* self, size_t pos, const CharT* text,
size_t num)
{
return self->insertChars (pos, text, num);
}
static void layout (StbTexteditRow* row, const TextEditorView* self, size_t start_i)
{
self->layout (row, start_i);
}
static float getCharWidth (const TextEditorView* self, size_t row, size_t pos)
{
return self->getCharWidth (row, pos);
}
static CharT getChar (const TextEditorView* self, int32_t pos) { return self->getChar (pos); }
static int32_t getLength (const TextEditorView* self) { return self->getLength (); }
static int moveToWordPrevious (const TextEditorView* self, size_t pos)
{
return static_cast<int> (self->moveToWordPrevious (pos));
}
static int moveToWordNext (const TextEditorView* self, size_t pos)
{
return static_cast<int> (self->moveToWordNext (pos));
}
static CharT* createUndoRecord (const TextEditorView* self, size_t pos, size_t insert_len,
size_t delete_len)
{
return self->createUndoRecord (pos, insert_len, delete_len);
}
static void undo (const TextEditorView* self) { self->doUndo (); }
static void redo (const TextEditorView* self) { self->doRedo (); }
protected:
// IFocusDrawing
bool drawFocusOnTop () override;
bool getFocusPath (CGraphicsPath& outPath) override;
// ITextEditor
bool setPlainText (std::string_view utf8Text) const override;
std::string getPlainText () const override;
void resetController () const override;
void setStyle (const Style& style) const override;
bool canHandleCommand (Command cmd) const override;
bool handleCommand (Command cmd) const override;
bool setCommandKeyBinding (Command cmd, char16_t character, VirtualKey virt,
Modifiers modifiers) const override;
void setFindOptions (FindOptions opt) const override;
void setFindString (std::string_view utf8Text) const override;
// TextEditorHighlighting::IEditorExt
std::u16string_view readText (size_t startOffset, size_t length) const override;
size_t getTextLength () const override;
// commandos
bool doShifting (bool right) const;
void selectAll () const;
bool doCut () const;
bool doCopy () const;
bool doPaste () const;
bool useSelectionForFind () const;
bool doFind (bool forward = true, size_t oldPos = String::npos) const;
bool showFindPanel () const;
String::size_type doFindCaseSensitive (bool forward) const;
String::size_type doFindIgnoreCase (bool forward) const;
// undo / redo
CharT* createUndoRecord (size_t pos, size_t insertLen, size_t deleteLen) const;
void checkCurrentUndoGroup (bool force) const;
void doUndo () const;
void doRedo () const;
template<bool iterateForward>
void doUndoRedo () const;
private:
template<typename Proc>
bool callSTB (Proc proc) const;
enum Dirty
{
UI = 1 << 0,
Layout = 1 << 1,
All = UI | Layout,
};
void validateLineStarts (Lines::const_iterator it, const Lines::const_iterator& end) const;
void invalidateSingleLine (size_t pos, int32_t numChars) const;
void invalidateSingleLine (Lines::iterator& line, int32_t numChars) const;
void invalidateLines (size_t pos, int32_t numChars) const;
void invalidate (Dirty what = Dirty::UI) const;
void invalidLine (size_t index, bool completeWidth = false) const;
void invalidLine (Lines::const_iterator it, bool completeWidth = false) const;
void invalidateRect (CRect r) const;
void invalidSelectedLines () const;
CCoord updateLineText (Lines::iterator& line) const;
CRect calculateLineRect (size_t index) const;
CRect calculateLineRect (Lines::const_iterator it) const;
CCoord calculateMaxWidth () const;
CRect calculateSelectionRect () const;
void updateLineNumbersView () const;
void layoutRows () const;
void onCursorChanged (int oldCursorPos, int newCursorPos) const;
void onSelectionChanged (Range newSel, bool forceInvalidation = false) const;
void selectOnDoubleClick (uint32_t clickCount) const;
template<bool forward>
void selectPair (size_t startPos, char16_t closingChar) const;
void updateSelectionOnDoubleClickMove (uint32_t clickCount) const;
void insertNewLine () const;
template<typename T>
T findLine (T begin, T end, size_t pos) const;
CRect calculateCursorRect (int cursor) const;
CRect invalidCursorRect () const;
void toggleCursorVisibility () const;
void restartBlinkTimer () const;
void onStyleChanged () const;
void setFindString (String&& text) const;
TextEditorView& mutableThis () const { return *const_cast<TextEditorView*> (this); }
public:
//------------------------------------------------------------------------
struct UndoRecord
{
size_t position {};
size_t deleted {0};
String characters;
};
using UndoRecords = std::vector<UndoRecord>;
//------------------------------------------------------------------------
struct UndoGroup
{
uint64_t time {0};
UndoRecords record;
};
using UndoList = std::vector<UndoGroup>;
//------------------------------------------------------------------------
struct ModelData
{
TextModel model;
std::shared_ptr<Style> style {std::make_shared<Style> ()};
ITextEditorController* controller {nullptr};
const IFontPainter* fontPainer {nullptr};
FindPanelController* findPanelController {nullptr};
CScrollView* scrollView {nullptr};
SharedPointer<LineNumberView> lineNumberView;
SharedPointer<CVSTGUITimer> blinkTimer;
CRect cursorRect {};
CRect lastDrawnCursorRect {};
Range selectedLines {};
CPoint lastMouse {MouseOutsidePos};
CCoord maxHeight {0};
CCoord maxWidth {200.};
CCoord horizontalLineMargin {0};
CCoord lineHeight {style->font->getSize () + style->lineSpacing};
CCoord fontAscent {0.};
CCoord fontDescent {0.};
STB_TexteditState editState {};
STB_TexteditState editStateOnMouseDown {};
bool mouseIsDown {false};
bool isInsertingText {false};
bool cursorIsVisible {false};
bool isInUndoRedo {false};
float cursorAlpha {0.f};
Lines::const_iterator stbInternalIterator;
FindOptions findOptions;
String findString;
CommandKeyArray commandKeys;
UndoList undoList {UndoGroup ()};
UndoList::iterator undoPos;
UndoGroup currentUndoGroup;
};
private:
mutable ModelData md;
};
#define VIRTUAL_KEY_BIT 0x80000000
#define STB_TEXTEDIT_K_SHIFT 0x40000000
#define STB_TEXTEDIT_K_CONTROL 0x20000000
#define STB_TEXTEDIT_K_ALT 0x10000000
// key-bindings
#define STB_TEXTEDIT_K_LEFT (VIRTUAL_KEY_BIT | VKEY_LEFT)
#define STB_TEXTEDIT_K_RIGHT (VIRTUAL_KEY_BIT | VKEY_RIGHT)
#define STB_TEXTEDIT_K_UP (VIRTUAL_KEY_BIT | VKEY_UP)
#define STB_TEXTEDIT_K_DOWN (VIRTUAL_KEY_BIT | VKEY_DOWN)
#if MAC
#define STB_TEXTEDIT_K_LINESTART (STB_TEXTEDIT_K_CONTROL | STB_TEXTEDIT_K_LEFT)
#define STB_TEXTEDIT_K_LINEEND (STB_TEXTEDIT_K_CONTROL | STB_TEXTEDIT_K_RIGHT)
#define STB_TEXTEDIT_K_WORDLEFT (STB_TEXTEDIT_K_ALT | STB_TEXTEDIT_K_LEFT)
#define STB_TEXTEDIT_K_WORDRIGHT (STB_TEXTEDIT_K_ALT | STB_TEXTEDIT_K_RIGHT)
#define STB_TEXTEDIT_K_TEXTSTART (STB_TEXTEDIT_K_CONTROL | STB_TEXTEDIT_K_UP)
#define STB_TEXTEDIT_K_TEXTEND (STB_TEXTEDIT_K_CONTROL | STB_TEXTEDIT_K_DOWN)
#else
#define STB_TEXTEDIT_K_LINESTART (VIRTUAL_KEY_BIT | VKEY_HOME)
#define STB_TEXTEDIT_K_LINEEND (VIRTUAL_KEY_BIT | VKEY_END)
#define STB_TEXTEDIT_K_WORDLEFT (STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_CONTROL)
#define STB_TEXTEDIT_K_WORDRIGHT (STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_CONTROL)
#define STB_TEXTEDIT_K_TEXTSTART (STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_CONTROL)
#define STB_TEXTEDIT_K_TEXTEND (STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_CONTROL)
#endif
#define STB_TEXTEDIT_K_DELETE (VIRTUAL_KEY_BIT | VKEY_DELETE)
#define STB_TEXTEDIT_K_BACKSPACE (VIRTUAL_KEY_BIT | VKEY_BACK)
#define STB_TEXTEDIT_K_UNDO (STB_TEXTEDIT_K_CONTROL | 'z')
#define STB_TEXTEDIT_K_REDO (STB_TEXTEDIT_K_CONTROL | STB_TEXTEDIT_K_SHIFT | 'z')
#define STB_TEXTEDIT_K_INSERT (VIRTUAL_KEY_BIT | VKEY_INSERT)
#define STB_TEXTEDIT_K_PGUP (VIRTUAL_KEY_BIT | VKEY_PAGEUP)
#define STB_TEXTEDIT_K_PGDOWN (VIRTUAL_KEY_BIT | VKEY_PAGEDOWN)
// functions
#define STB_TEXTEDIT_STRINGLEN(tc) TextEditorView::getLength (tc)
#define STB_TEXTEDIT_LAYOUTROW TextEditorView::layout
#define STB_TEXTEDIT_GETWIDTH(tc, n, i) TextEditorView::getCharWidth (tc, n, i)
#define STB_TEXTEDIT_KEYTOTEXT(key) \
((key & VIRTUAL_KEY_BIT) ? 0 : ((key & STB_TEXTEDIT_K_CONTROL) ? 0 : (key & (~0xF0000000))));
#define STB_TEXTEDIT_GETCHAR(tc, i) TextEditorView::getChar (tc, i)
#define STB_TEXTEDIT_NEWLINE '\n'
#define STB_TEXTEDIT_DELETECHARS TextEditorView::deleteChars
#define STB_TEXTEDIT_INSERTCHARS TextEditorView::insertChars
#define STB_TEXTEDIT_MOVEWORDLEFT TextEditorView::moveToWordPrevious
#define STB_TEXTEDIT_MOVEWORDRIGHT TextEditorView::moveToWordNext
#define STB_TEXTEDIT_CUSTOM_CREATEUNDO TextEditorView::createUndoRecord
#define STB_TEXTEDIT_CUSTOM_UNDO TextEditorView::undo
#define STB_TEXTEDIT_CUSTOM_REDO TextEditorView::redo
#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.f
#define STB_TEXTEDIT_IMPLEMENTATION
#include "platform/common/stb_textedit.h"
#undef STB_TEXTEDIT_IMPLEMENTATION
//------------------------------------------------------------------------
struct LineNumberView : CView,
ViewListenerAdapter
{
LineNumberView (CView* textEditorView);
~LineNumberView () noexcept override;
void drawRect (CDrawContext* context, const CRect& dirtyRect) override;
void setStyle (const std::shared_ptr<ITextEditor::Style>& newStyle, CCoord newLineHeight);
void setNumLines (size_t numberOfLines);
void setSelectedLines (Range range);
private:
void viewSizeChanged (CView* view, const CRect& oldSize) override;
void viewWillDelete (CView* view) override;
std::shared_ptr<ITextEditor::Style> style;
CCoord lineHeight {};
size_t numLines {0};
Range selectedLines {};
CView* textEditorView {nullptr};
};
//------------------------------------------------------------------------
struct FindPanelController : IControlListener,
ViewListenerAdapter,
ViewEventListenerAdapter
{
using RemoveFindPanelFunc = std::function<void ()>;
static CViewContainer* makeFindPanelView (CRect rect, TextEditorView::ModelData& md,
const ITextEditor& editor, RemoveFindPanelFunc&& f);
void setFindString (StringView text);
void setFindOptions (ITextEditor::FindOptions opt);
private:
enum Tag
{
Textfield,
CloseButton,
WholeWords,
CaseSensitive,
FindPrevious,
FindNext,
};
FindPanelController (const ITextEditor& editor);
~FindPanelController () noexcept;
void valueChanged (CControl* control) override;
void viewLostFocus (CView* view) override;
void viewWillDelete (CView* view) override;
void viewOnEvent (CView* view, Event& event) override;
const ITextEditor& editor;
CTextEdit* editfield {nullptr};
CControl* closeBox {nullptr};
CControl* caseSensitiveButton {nullptr};
CControl* wholeWordButton {nullptr};
ITextEditor::FindOptions findOptions {};
CommandKeyArray commandKeys;
RemoveFindPanelFunc removeFindPanelFunc;
};
static constexpr size_t Index (ITextEditor::Command cmd) { return static_cast<size_t> (cmd); }
//------------------------------------------------------------------------
TextEditorView::TextEditorView (ITextEditorController* controller) : CView ({0, 0, 10, 10})
{
md.controller = controller;
md.undoPos = md.undoList.end ();
setWantsFocus (true);
onStyleChanged ();
stb_textedit_initialize_state (&md.editState, false);
std::fill (md.commandKeys.begin (), md.commandKeys.end (), Key ());
md.commandKeys[Index (Command::SelectAll)] = {u'a', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::Cut)] = {u'x', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::Copy)] = {u'c', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::Paste)] = {u'v', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::Undo)] = {u'z', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::Redo)] = {
u'z', VirtualKey::None, {ModifierKey::Control, ModifierKey::Shift}};
#if MAC
md.commandKeys[Index (Command::FindNext)] = {u'g', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::FindPrevious)] = {
u'g', VirtualKey::None, {ModifierKey::Control, ModifierKey::Shift}};
md.commandKeys[Index (Command::UseSelectionForFind)] = {
u'e', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::ShiftLeft)] = {u'[', VirtualKey::None, {ModifierKey::Control}};
md.commandKeys[Index (Command::ShiftRight)] = {u']', VirtualKey::None, {ModifierKey::Control}};
#else
md.commandKeys[Index (Command::FindNext)] = {0, VirtualKey::F3, {}};
md.commandKeys[Index (Command::FindPrevious)] = {0, VirtualKey::F3, {ModifierKey::Shift}};
md.commandKeys[Index (Command::UseSelectionForFind)] = {
0, VirtualKey::F3, {ModifierKey::Control}};
md.commandKeys[Index (Command::ShiftLeft)] = {0, VirtualKey::Tab, {ModifierKey::Shift}};
md.commandKeys[Index (Command::ShiftRight)] = {0, VirtualKey::Tab, {}};
#endif
md.commandKeys[Index (Command::ShowFindPanel)] = {
u'f', VirtualKey::None, {ModifierKey::Control}};
md.controller->onTextEditorCreated (*this);
}
//------------------------------------------------------------------------
void TextEditorView::beforeDelete ()
{
if (md.controller)
md.controller->onTextEditorDestroyed (*this);
CView::beforeDelete ();
}
//------------------------------------------------------------------------
bool TextEditorView::attached (CView* parent)
{
if (CView::attached (parent))
{
if (auto sv = dynamic_cast<CScrollView*> (parent->getParentView ()))
{
md.scrollView = sv;
layoutRows ();
md.scrollView->registerViewEventListener (this);
if (auto sb = md.scrollView->getVerticalScrollbar ())
sb->registerViewEventListener (this);
if (md.style->showLineNumbers)
{
md.lineNumberView = makeOwned<LineNumberView> (this);
md.lineNumberView->setStyle (md.style, md.lineHeight);
updateLineNumbersView ();
md.scrollView->setEdgeView (CScrollView::Edge::Left, md.lineNumberView);
md.lineNumberView->remember ();
}
}
return true;
}
return false;
}
//------------------------------------------------------------------------
bool TextEditorView::removed (CView* parent)
{
if (md.scrollView)
{
md.scrollView->unregisterViewEventListener (this);
if (auto sb = md.scrollView->getVerticalScrollbar ())
sb->unregisterViewEventListener (this);
}
md.scrollView = nullptr;
md.blinkTimer = nullptr;
md.lineNumberView = nullptr;
return CView::removed (parent);
}
//------------------------------------------------------------------------
void TextEditorView::takeFocus ()
{
if (md.lastMouse != MouseOutsidePos)
getFrame ()->setCursor (kCursorIBeam);
restartBlinkTimer ();
}
//------------------------------------------------------------------------
void TextEditorView::looseFocus ()
{
md.blinkTimer = nullptr;
md.cursorIsVisible = true;
toggleCursorVisibility ();
}
//------------------------------------------------------------------------
void TextEditorView::parentSizeChanged ()
{
if (md.scrollView)
{
auto func = [This = shared (this), makeCursorVisible = md.isInsertingText] () mutable {
if (!This->isAttached () || !This->md.scrollView)
return;
auto viewSize = This->getViewSize ();
viewSize.setHeight (This->md.maxHeight);
viewSize.setWidth (This->md.maxWidth);
auto containerSize = This->md.scrollView->calculateOptimalContainerSize ();
if (containerSize.getWidth () > viewSize.getWidth ())
{
if (viewSize.getHeight () > containerSize.getHeight ())
viewSize.setWidth (containerSize.getWidth () -
This->md.scrollView->getScrollbarWidth ());
else
viewSize.setWidth (containerSize.getWidth ());
}
if (containerSize.getHeight () > viewSize.getHeight ())
{
if (viewSize.getWidth () > containerSize.getWidth ())
viewSize.setHeight (containerSize.getHeight () -
This->md.scrollView->getScrollbarWidth ());
else
viewSize.setHeight (containerSize.getHeight ());
}
This->setViewSize (viewSize);
if (makeCursorVisible)
This->onCursorChanged (-1, This->md.editState.cursor);
This->md.editState.row_count_per_page = static_cast<int> (
std::ceil (This->getVisibleViewSize ().getHeight () / This->md.lineHeight));
};
auto frame = getFrame ();
if (frame && frame->inEventProcessing ())
{
frame->doAfterEventProcessing (func);
return;
}
else
{
func ();
}
}
else
{
auto viewSize = getViewSize ();
viewSize.setHeight (md.maxHeight);
viewSize.setWidth (md.maxWidth);
setViewSize (viewSize);
}
}
//------------------------------------------------------------------------
bool TextEditorView::drawFocusOnTop () { return true; }
//------------------------------------------------------------------------
bool TextEditorView::getFocusPath (CGraphicsPath& outPath)
{
auto r = getVisibleViewSize ();
outPath.addRect (r);
CCoord focusWidth = getFrame ()->getFocusWidth ();
r.inset (focusWidth, focusWidth);
outPath.addRect (r);
return true;
}
//------------------------------------------------------------------------
void TextEditorView::viewOnEvent (CView* view, Event& event)
{
if (event.type != EventType::MouseWheel)
return;
auto& wheelEvent = castMouseWheelEvent (event);
CPoint scrollOffset {};
if (wheelEvent.flags & MouseWheelEvent::Flags::PreciseDeltas)
{
scrollOffset.x += std::ceil (wheelEvent.deltaX / 0.1);
scrollOffset.y -= std::ceil (wheelEvent.deltaY / 0.1);
}
else
{
scrollOffset.x += wheelEvent.deltaX * md.lineHeight;
scrollOffset.y -= wheelEvent.deltaY * md.lineHeight;
}
if (wheelEvent.flags & MouseWheelEvent::DirectionInvertedFromDevice)
{
scrollOffset.y *= -1.;
}
auto viewSize = getVisibleViewSize ();
viewSize.offset (scrollOffset);
md.scrollView->makeRectVisible (viewSize);
event.consumed = true;
}
//------------------------------------------------------------------------
void TextEditorView::onStyleChanged () const
{
if (auto pf = md.style->font->getPlatformFont ())
{
md.fontAscent = pf->getAscent ();
md.fontDescent = pf->getDescent ();
md.lineHeight =
std::round ((md.fontAscent + md.fontDescent + md.style->lineSpacing) * 2.) / 2.;
}
else
{
md.lineHeight = md.style->font->getSize () + md.style->lineSpacing;
}
md.fontPainer = md.style->font->getFontPainter ();
if (md.lineNumberView)
{
if (md.style->showLineNumbers)
{
md.lineNumberView->setStyle (md.style, md.lineHeight);
updateLineNumbersView ();
}
else if (md.scrollView)
{
md.scrollView->setEdgeView (CScrollView::Edge::Left, nullptr);
md.lineNumberView = nullptr;
}
}
else if (md.style->showLineNumbers && md.scrollView)
{
md.lineNumberView = makeOwned<LineNumberView> (&mutableThis ());
md.lineNumberView->setStyle (md.style, md.lineHeight);
updateLineNumbersView ();
md.scrollView->setEdgeView (CScrollView::Edge::Left, md.lineNumberView);
md.lineNumberView->remember ();
}
md.horizontalLineMargin = md.style->leftMargin * 2.;
invalidate (Dirty::All);
}
//------------------------------------------------------------------------
void TextEditorView::setStyle (const Style& newStyle) const
{
if (!md.style->font)
return;
md.style = std::make_shared<Style> (newStyle);
onStyleChanged ();
}
//------------------------------------------------------------------------
bool TextEditorView::setPlainText (std::string_view utf8Text) const
{
md.model.text = convert (utf8Text.data (), utf8Text.size ());
invalidate (Dirty::All);
if (md.lineNumberView)
updateLineNumbersView ();
return true;
}
//------------------------------------------------------------------------
std::string TextEditorView::getPlainText () const { return convert (md.model.text); }
//------------------------------------------------------------------------
void TextEditorView::resetController () const { md.controller = nullptr; }
//------------------------------------------------------------------------
bool TextEditorView::canHandleCommand (Command cmd) const
{
switch (cmd)
{
case Command::SelectAll:
return true;
case Command::UseSelectionForFind:
[[fallthrough]];
case Command::Cut:
[[fallthrough]];
case Command::Copy:
{
return md.editState.select_start != md.editState.select_end;
}
case Command::Paste:
{
if (auto clipboard = getFrame ()->getClipboard ())
{
auto count = clipboard->getCount ();
for (auto i = 0u; i < count; ++i)
{
if (clipboard->getDataType (i) == IDataPackage::kText)
return true;
}
}
return false;
}
case Command::Undo:
{
// TODO:
return true;
}
case Command::Redo:
{
// TODO:
return true;
}
case Command::ShiftLeft:
return true;
case Command::ShiftRight:
return true;
case Command::TakeFocus:
return true;
case Command::FindNext:
[[fallthrough]];
case Command::FindPrevious:
{
return !md.findString.empty ();
}
case Command::ShowFindPanel:
return md.scrollView != nullptr;
}
return false;
}
//------------------------------------------------------------------------
bool TextEditorView::handleCommand (Command cmd) const
{
auto doFinally = finally ([&] () {
if (getFrame ()->getFocusView () == this)
{
restartBlinkTimer ();
}
});
switch (cmd)
{
case Command::ShiftLeft:
return doShifting (false);
case Command::ShiftRight:
return doShifting (true);
case Command::SelectAll:
selectAll ();
return true;
case Command::Cut:
return doCut ();
case Command::Copy:
return doCopy ();
case Command::Paste:
return doPaste ();
case Command::Undo:
return callSTB ([=] () { stb_text_undo (this, &md.editState); });
case Command::Redo:
return callSTB ([=] () { stb_text_redo (this, &md.editState); });
case Command::FindNext:
return doFind (true);
case Command::FindPrevious:
return doFind (false);
case Command::UseSelectionForFind:
return useSelectionForFind ();
case Command::ShowFindPanel:
return showFindPanel ();
case Command::TakeFocus:
{
if (auto frame = getFrame ())
{
if (frame->getFocusView () != this)
frame->setFocusView (&mutableThis ());
}
return true;
}
}
return false;
}
//------------------------------------------------------------------------
bool TextEditorView::setCommandKeyBinding (Command cmd, char16_t character, VirtualKey virt,
Modifiers modifiers) const
{
md.commandKeys[Index (cmd)] = {character, virt, modifiers};
return true;
}
//------------------------------------------------------------------------
std::u16string_view TextEditorView::readText (size_t startOffset, size_t length) const
{
if (startOffset >= md.model.text.length () || md.model.lines.empty ())
return {};
if (startOffset + length >= md.model.text.length ())
length = md.model.text.length () - startOffset;
return {md.model.text.data () + startOffset, length};
}
//------------------------------------------------------------------------
size_t TextEditorView::getTextLength () const { return md.model.text.length (); }
//------------------------------------------------------------------------
inline Range toLineSelection (const Range& line, size_t selStart, size_t selEnd)
{
if (selStart == selEnd)
return {};
if (selStart > selEnd)
std::swap (selStart, selEnd);
if (selEnd < line.start)
return {};
if (selStart >= line.start + line.length)
return {};
size_t lineStart = line.start;
size_t lineLength = selEnd - selStart;
if (selStart > line.start)
lineStart = selStart;
else if (selStart < line.start)
lineLength -= line.start - selStart;
if (lineStart + lineLength > line.start + line.length)
lineLength = line.start + line.length - lineStart;
return {lineStart - line.start, lineLength};
}
//------------------------------------------------------------------------
void TextEditorView::drawRect (CDrawContext* context, const CRect& dirtyRect)
{
context->setFillColor (md.style->backColor);
context->setDrawMode (kAntiAliasing);
context->drawRect (dirtyRect, kDrawFilled);
auto styleProvider = dynamic_cast<TextEditorColorization::IStyleProvider*> (md.controller);
if (styleProvider)
styleProvider->beginDraw (*this);
CCoord x = getViewSize ().left + md.style->leftMargin;
CCoord y = getViewSize ().top - md.style->lineSpacing;
for (auto index = 0u; index < md.model.lines.size (); ++index)
{
const auto& line = md.model.lines[index];
if (y > dirtyRect.bottom)
break;
y += md.lineHeight;
if (y < dirtyRect.top)
continue;
context->setFontColor (md.style->textColor);
context->setFont (md.style->font);
auto selRange =
toLineSelection (line.range, md.editState.select_start, md.editState.select_end);
if (selRange)
{
auto selX = x;
if (selRange.start != 0)
{
auto t = md.model.text.substr (line.range.start, selRange.start);
auto nonSelectedText = convert (t);
replaceTabs (nonSelectedText, md.style->tabWidth);
selX += context->getStringWidth (nonSelectedText.data ());
}
CRect r (selX, y - md.fontAscent, selX, y + md.fontDescent);
if (selRange.start + selRange.length >= line.range.length &&
(line.range.length > 0 && md.model.text[line.range.end () - 1] == u'\n'))
r.right = getViewSize ().right;
else
{
auto t = md.model.text.substr (line.range.start + selRange.start, selRange.length);
auto selectedText = convert (t);
replaceTabs (selectedText, md.style->tabWidth);
r.setWidth (context->getStringWidth (selectedText.data ()));
}
r.inset (0, -md.style->lineSpacing / 2.);
context->setFillColor (md.style->selectionBackColor);
context->drawRect (r, kDrawFilled);
}
if (styleProvider)
{
auto lineX = x;
auto styles = styleProvider->getStyles (*this, line.range.start, line.range.length);
size_t start = line.range.start;
size_t end = 0u;
std::string tmpStr;
for (const auto& style : styles)
{
if (style.start != start)
{