Repository navigation
Expand file tree
/
Copy pathtext.cpp
More file actions
1526 lines (1416 loc) · 51.4 KB
/
Copy pathtext.cpp
File metadata and controls
1526 lines (1416 loc) · 51.4 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
//+----------------------------------------------------------------------------+
//| Description: Magic Set Editor - Program to make Magic (tm) cards |
//| Copyright: (C) 2001 - 2012 Twan van Laarhoven and Sean Hunt |
//| License: GNU General Public License 2 or later (see file COPYING) |
//+----------------------------------------------------------------------------+
// ----------------------------------------------------------------------------- : Includes
#include <util/prec.hpp>
#include <gui/value/text.hpp>
#include <gui/icon_menu.hpp>
#include <gui/util.hpp>
#include <gui/drop_down_list.hpp>
#include <data/word_list.hpp>
#include <data/game.hpp>
#include <data/settings.hpp>
#include <data/action/value.hpp>
#include <util/tagged_string.hpp>
#include <util/find_replace.hpp>
#include <util/spell_checker.hpp>
#include <util/window_id.hpp>
#include <wx/clipbrd.h>
#include <wx/caret.h>
#undef small // some evil windows header defines this
using std::max;
using std::min;
using std::swap;
using std::pair;
DECLARE_SHARED_POINTER_TYPE(DropDownList);
struct DropDownWordListItem;
// ----------------------------------------------------------------------------- : TextValueEditorScrollBar
/// A scrollbar to scroll a TextValueEditor
/** implemented as the scrollbar of a Window because that functions better */
class TextValueEditorScrollBar : public wxWindow {
public:
TextValueEditorScrollBar(TextValueEditor& tve);
private:
DECLARE_EVENT_TABLE();
TextValueEditor& tve;
void onScroll(wxScrollWinEvent&);
void onMotion(wxMouseEvent&);
};
TextValueEditorScrollBar::TextValueEditorScrollBar(TextValueEditor& tve)
: wxWindow(&tve.editor(), wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER | wxVSCROLL | wxALWAYS_SHOW_SB)
, tve(tve)
{}
void TextValueEditorScrollBar::onScroll(wxScrollWinEvent& ev) {
if (ev.GetOrientation() == wxVERTICAL) {
tve.scrollTo(ev.GetPosition());
}
}
void TextValueEditorScrollBar::onMotion(wxMouseEvent& ev) {
tve.editor().SetCursor(*wxSTANDARD_CURSOR);
ev.Skip();
}
BEGIN_EVENT_TABLE(TextValueEditorScrollBar, wxEvtHandler)
EVT_SCROLLWIN (TextValueEditorScrollBar::onScroll)
EVT_MOTION (TextValueEditorScrollBar::onMotion)
END_EVENT_TABLE ()
// ----------------------------------------------------------------------------- : WordListPos
class WordListPos : public IntrusivePtrBase<WordListPos> {
public:
WordListPos(size_t start, size_t end, WordListP word_list)
: start(start), end(end)
, rect(-1,-1,-1,-1)
, word_list(word_list)
{}
const size_t start, end; ///< Start and ending indices
RealRect rect; ///< Rectangle around word list text
WordListP word_list; ///< Word list to use
Bitmap behind; ///< Bitmap behind the button
};
enum WordListItemFlags
{ FLAG_ACTIVE = 0x01
, FLAG_SUBMENU = 0x02
, FLAG_LINE_BELOW = 0x04
};
struct DropDownWordListItem {
DropDownWordListItem() : flags(0) {}
DropDownWordListItem(WordListWordP word, int flags = 0)
: word(word)
, name(word->name)
, flags(flags | (word->isGroup() * FLAG_SUBMENU)
| (word->line_below * FLAG_LINE_BELOW))
{}
DropDownWordListItem(WordListWordP word, const String& name, int flags = 0)
: word(word)
, name(name)
, flags(flags)
{}
WordListWordP word;
String name;
int flags;
DropDownWordListP submenu;
inline bool active() const { return flags & FLAG_ACTIVE; }
inline void setActive(bool a) { flags = (flags & ~FLAG_ACTIVE) | a * FLAG_ACTIVE; }
};
class DropDownWordList : public DropDownList {
public:
DropDownWordList(Window* parent, bool is_submenu, TextValueEditor& tve, const WordListPosP& pos, const WordListWordP& list);
void setWords(const WordListWordP& words2);
void setWords(const WordListPosP& pos2);
inline WordListPosP getPos() const { return pos; }
protected:
virtual void redrawArrowOnParent();
virtual size_t itemCount() const { return items.size(); }
virtual bool lineBelow(size_t item) const { return items[item].flags & FLAG_LINE_BELOW; }
virtual String itemText(size_t item) const { return items[item].name; }
virtual void drawIcon(DC& dc, int x, int y, size_t item, bool selected) const;
virtual DropDownList* submenu(size_t item) const;
virtual size_t selection() const;
virtual void select(size_t item);
virtual bool stayOpen(size_t selection) const;
private:
TextValueEditor& tve;
WordListPosP pos;
WordListWordP words; ///< The words we are listing
bool has_checkboxes; ///< Do we need checkboxes?
mutable vector <DropDownWordListItem> items;
void addWordsFromScript(const WordListWordP& w);
};
DropDownWordList::DropDownWordList(Window* parent, bool is_submenu, TextValueEditor& tve, const WordListPosP& pos, const WordListWordP& words)
: DropDownList(parent, is_submenu, is_submenu ? nullptr : &tve)
, tve(tve), pos(pos)
, has_checkboxes(false)
{
setWords(words);
}
void DropDownWordList::setWords(const WordListPosP& pos2) {
setWords((WordListWordP)pos2->word_list);
pos = pos2;
}
void DropDownWordList::setWords(const WordListWordP& words2) {
if (words == words2) return;
// switch to different list
items.clear();
words = words2;
// init items; do we need checkboxes?
// do we need checkboxes?
has_checkboxes = false;
for(auto& w : words->words) {
if (w->is_prefix) has_checkboxes = true;
if (w->script) {
addWordsFromScript(w);
} else {
// only if not duplicating
bool already_added = false;
for(auto& i :items) {
if (i.name == w->name) {
already_added = true;
break;
}
}
if (!already_added || w->isGroup()) {
items.push_back(DropDownWordListItem(w));
}
}
}
// size of items
icon_size.width = has_checkboxes ? 16 : 0;
item_size.height = max(16., item_size.height);
}
void DropDownWordList::addWordsFromScript(const WordListWordP& w) {
assert(w->script);
// run script
Context& ctx = tve.viewer.getContext();
String str = w->script.invoke(ctx)->toString();
// collect items
vector<String> strings;
{
size_t prev = 0;
size_t comma = str.find_first_of(_(','));
while (comma != String::npos) {
strings.push_back(str.substr(prev, comma - prev));
prev = comma + 1;
if (prev + 1 < str.size() && str.GetChar(prev + 1) == _(' ')) ++prev; // skip space after comma
comma = str.find_first_of(_(','), prev);
}
strings.push_back(str.substr(prev));
sort(strings.begin(), strings.end());
}
// add to menu
size_t prev = items.size();
for(auto& s : strings) {
if (prev >= items.size() || s != items[prev].name) {
// no line below prev
if (prev < items.size() && !items[prev].name.empty()) {
items[prev].flags = 0;
}
// not a duplicate
prev = items.size();
items.push_back(DropDownWordListItem(w, s, w->line_below * FLAG_LINE_BELOW));
}
}
}
void DropDownWordList::drawIcon(DC& dc, int x, int y, size_t item, bool selected) const {
if (has_checkboxes) {
bool radio = !words->words[item]->is_prefix;
// draw checkbox
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
dc.DrawRectangle(x,y,16,16);
wxRect rect = RealRect(x+2,y+2,12,12);
if (radio) {
draw_radiobox(nullptr, dc, rect, items[item].active(), itemEnabled(item));
} else {
draw_checkbox(nullptr, dc, rect, items[item].active(), itemEnabled(item));
}
}
}
DropDownList* DropDownWordList::submenu(size_t item) const {
DropDownWordListItem& i = items[item];
if (i.submenu) {
// make sure the members of the submenu are still up to date (in particular the pos, see #13)
i.submenu->pos = pos;
return i.submenu.get();
}
if (i.flags & FLAG_SUBMENU) {
// create submenu?
if (!i.submenu) {
i.submenu.reset(new DropDownWordList(const_cast<DropDownWordList*>(this), true, tve, pos, i.word));
}
return i.submenu.get();
} else {
return nullptr;
}
}
size_t DropDownWordList::selection() const {
// current selection
String current = untag(tve.value().value->toString().substr(pos->start, pos->end - pos->start));
// find selection
size_t selected = NO_SELECTION;
bool prefix_selected = true;
size_t n = 0;
for(auto& item : items) {
if (item.word->is_prefix) {
if (starts_with(current, item.name)) {
item.setActive(true);
current = current.substr(item.name.size());
} else {
item.setActive(false);
}
} else {
item.setActive((current == item.name));
}
if (item.active() && (selected == NO_SELECTION || (prefix_selected && !item.word->is_prefix))) {
selected = n;
prefix_selected = item.word->is_prefix;
}
++n;
}
return selected;
}
void DropDownWordList::select(size_t item) {
// determine new value
String new_value;
bool toggling_prefix = items[item].word->is_prefix;
for (size_t i = 0 ; i < items.size() ; ++i) {
const DropDownWordListItem& it = items[i];
if (it.word->is_prefix) {
if (it.active() != (i == item)) {
new_value += it.name;
}
} else {
if (i == item || (toggling_prefix && items[i].active())) {
new_value += it.name;
}
}
}
// set value
tve.selection_start_i = pos->start;
tve.selection_end_i = pos->end;
tve.fixSelection(TYPE_INDEX);
tve.replaceSelection(escape(new_value), _ACTION_1_("change", tve.field().name));
// stay open?
if (IsShown()) selection(); // update 'enabled'
}
bool DropDownWordList::stayOpen(size_t selection) const {
if (selection == NO_SELECTION) return false;
return items[selection].word->is_prefix;
}
void DropDownWordList::redrawArrowOnParent() {
tve.redrawWordListIndicators(true);
}
// ----------------------------------------------------------------------------- : TextValueEditor
IMPLEMENT_VALUE_EDITOR(Text)
, selection_start (0), selection_end (0)
, selection_start_i(0), selection_end_i(0)
, selecting(false), select_words(false)
, scrollbar(nullptr), scroll_with_cursor(false)
, hovered_words(nullptr)
{
if (viewer.nativeLook() && field().multi_line) {
scrollbar = new TextValueEditorScrollBar(*this);
style->padding_right = max(style->padding_right(), (double)scrollbar->GetSize().x);
}
}
TextValueEditor::~TextValueEditor() {
delete scrollbar;
}
// ----------------------------------------------------------------------------- : Mouse
bool TextValueEditor::onLeftDown(const RealPoint& pos, wxMouseEvent& ev) {
select_words = false;
// on word list dropdown button?
WordListPosP wl_pos = findWordList(pos);
if (wl_pos) {
wordListDropDown(wl_pos);
} else {
// no, select text
selecting = true;
moveSelection(TYPE_INDEX, v.indexAt(pos), !ev.ShiftDown(), MOVE_MID);
}
return true;
}
bool TextValueEditor::onLeftUp(const RealPoint& pos, wxMouseEvent&) {
// TODO: lookup position of click?
selecting = false;
return false;
}
bool TextValueEditor::onMotion(const RealPoint& pos, wxMouseEvent& ev) {
if (dropDownShown()) return false;
if (ev.LeftIsDown() && selecting) {
size_t index = v.indexAt(pos);
if (select_words) {
// on the left, swap start and end
bool left = selection_end_i < selection_start_i;
size_t next = nextWordBoundary(index);
size_t prev = prevWordBoundary(index);
if (( left && next > max(selection_start_i, selection_end_i)) ||
(!left && prev < min(selection_start_i, selection_end_i))) {
left = !left;
swap(selection_start_i, selection_end_i);
}
// TODO : still not quite right, requires a moveSelection function that moves start & end simultaniously
moveSelection(TYPE_INDEX, left ? prev : next, false, MOVE_MID);
} else {
moveSelection(TYPE_INDEX, index, false, MOVE_MID);
}
}
return true;
}
void TextValueEditor::onMouseLeave(const RealPoint& pos, wxMouseEvent& ev) {
if (hovered_words) {
hovered_words = nullptr;
redrawWordListIndicators();
}
}
bool TextValueEditor::onLeftDClick(const RealPoint& pos, wxMouseEvent& ev) {
if (dropDownShown()) return false;
select_words = true;
selecting = true;
size_t index = v.indexAt(pos);
moveSelection(TYPE_INDEX, prevWordBoundary(index), true, MOVE_MID);
moveSelection(TYPE_INDEX, nextWordBoundary(index), false, MOVE_MID);
return true;
}
bool TextValueEditor::onRightDown(const RealPoint& pos, wxMouseEvent& ev) {
if (dropDownShown()) return false;
size_t index = v.indexAt(pos);
if (index < min(selection_start_i, selection_end_i) ||
index > max(selection_start_i, selection_end_i)) {
// only move cursor when outside selection
moveSelection(TYPE_INDEX, index, !ev.ShiftDown(), MOVE_MID);
}
return true;
}
// ----------------------------------------------------------------------------- : Keyboard
bool TextValueEditor::onChar(wxKeyEvent& ev) {
if (dropDownShown()) {
// forward to drop down list
return drop_down->onCharInParent(ev);
}
if (ev.AltDown() && isAlpha((Char)ev.GetKeyCode())) {
// this looks like an accelerator
ev.Skip();
return false;
}
fixSelection();
switch (ev.GetKeyCode()) {
case WXK_LEFT:
// move left (selection?)
if (ev.ControlDown()) {
moveSelection(TYPE_INDEX, prevWordBoundary(selection_end_i),!ev.ShiftDown(), MOVE_LEFT);
} else {
moveSelection(TYPE_CURSOR, prevCharBoundary(selection_end), !ev.ShiftDown(), MOVE_LEFT);
}
break;
case WXK_RIGHT:
// move left (selection?)
if (ev.ControlDown()) {
moveSelection(TYPE_INDEX, nextWordBoundary(selection_end_i),!ev.ShiftDown(), MOVE_RIGHT);
} else {
moveSelection(TYPE_CURSOR, nextCharBoundary(selection_end), !ev.ShiftDown(), MOVE_RIGHT);
}
break;
case WXK_UP:
if ( wordListDropDown(findWordList(selection_end_i)) ) break;
moveSelection(TYPE_INDEX, v.moveLine(selection_end_i, -1), !ev.ShiftDown(), MOVE_LEFT_OPT);
break;
case WXK_DOWN:
if ( wordListDropDown(findWordList(selection_end_i)) ) break;
moveSelection(TYPE_INDEX, v.moveLine(selection_end_i, +1), !ev.ShiftDown(), MOVE_RIGHT_OPT);
break;
case WXK_HOME:
// move to begining of line / all (if control)
if (ev.ControlDown()) {
moveSelection(TYPE_INDEX, 0, !ev.ShiftDown(), MOVE_LEFT_OPT);
} else {
moveSelection(TYPE_INDEX, v.lineStart(selection_end_i), !ev.ShiftDown(), MOVE_LEFT_OPT);
}
break;
case WXK_END:
// move to end of line / all (if control)
if (ev.ControlDown()) {
moveSelection(TYPE_INDEX, value().value->toString().size(), !ev.ShiftDown(), MOVE_RIGHT_OPT);
} else {
moveSelection(TYPE_INDEX, v.lineEnd(selection_end_i), !ev.ShiftDown(), MOVE_RIGHT_OPT);
}
break;
case WXK_BACK:
if (selection_start == selection_end) {
// if no selection, select previous character
moveSelectionNoRedraw(TYPE_CURSOR, prevCharBoundary(selection_end), false);
if (selection_start == selection_end) {
// Walk over a <sep> as if we are the LEFT key
moveSelection(TYPE_CURSOR, prevCharBoundary(selection_end), true, MOVE_LEFT);
return true;
}
}
replaceSelection(wxEmptyString, _ACTION_("backspace"));
break;
case WXK_DELETE:
if (selection_start == selection_end) {
// if no selection select next
moveSelectionNoRedraw(TYPE_CURSOR, nextCharBoundary(selection_end), false);
if (selection_start == selection_end) {
// Walk over a <sep> as if we are the RIGHT key
moveSelection(TYPE_CURSOR, nextCharBoundary(selection_end), true, MOVE_RIGHT);
}
}
replaceSelection(wxEmptyString, _ACTION_("delete"));
break;
case WXK_RETURN:
if (field().multi_line) {
if (ev.ShiftDown()) {
// soft line break
replaceSelection(_("<soft-line>\n</soft-line>"), _ACTION_("soft line break"));
} else {
replaceSelection(_("\n"), _ACTION_("enter"));
}
}
break;
default:
#ifdef __WXMSW__
if (ev.GetKeyCode() >= _(' ') && ev.GetKeyCode() == (int)ev.GetRawKeyCode()) {
// This check is need, otherwise pressing a key, say "0" on the numpad produces "a0"
// (don't ask me why)
#else
if (ev.GetKeyCode() >= _(' ') /*&& ev.GetKeyCode() == (int)ev.GetRawKeyCode()*/) {
#endif
// TODO: Find a more correct way to determine normal characters,
// this might not work for internationalized input.
// It might also not be portable!
#ifdef UNICODE
replaceSelection(escape(String(ev.GetUnicodeKey(), 1)), _ACTION_("typing"), true);
#else
replaceSelection(escape(String((Char)ev.GetKeyCode(), 1)), _ACTION_("typing"), true);
#endif
} else {
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------- : Spellchecking
String spellcheck_word_at(const String& str, size_t start) {
size_t end = min(match_close_tag(str,start), str.size());
return untag(str.substr(start,end-start));
}
void spellcheck_language_at(const String& str, size_t error_pos, SpellChecker** out) {
String tag = tag_at(str,error_pos);
size_t pos = min(tag.find_first_of(_(':')), tag.size()-1);
size_t pos2 = min(tag.find_first_of(_(':'),pos+1), tag.size());
String language = tag.substr(pos+1,pos2-pos-1);
if (language.empty()) return;
out[0] = &SpellChecker::get(language);
if (pos2 >= tag.size()) return;
String extra = tag.substr(pos2+1);
if (extra.empty()) return;
out[1] = &SpellChecker::get(extra,language);
}
void get_spelling_suggestions(const String& str, size_t error_pos, vector<String>& suggestions_out) {
String word = spellcheck_word_at(str, error_pos);
// find dictionaries
SpellChecker* checkers[3] = {nullptr};
spellcheck_language_at(str, error_pos, checkers);
// suggestions
for (size_t i = 0 ; checkers[i] ; ++i) {
checkers[i]->suggest(word, suggestions_out);
}
}
// ----------------------------------------------------------------------------- : Other events
void TextValueEditor::onFocus() {
showCaret();
}
void TextValueEditor::onLoseFocus() {
// hide caret
wxCaret* caret = editor().GetCaret();
assert(caret);
if (caret->IsVisible()) caret->Hide();
// hide selection
//selection_start = selection_end = 0;
//selection_start_i = selection_end_i = 0;
}
bool TextValueEditor::onContextMenu(IconMenu& m, wxContextMenuEvent& ev) {
// in a keword? => "reminder text" option
String val = value().value->toString();
size_t kwpos = in_tag(val, _("<kw-"), selection_start_i, selection_start_i);
if (kwpos != String::npos) {
m.InsertSeparator(0);
m.Insert(0,ID_FORMAT_REMINDER, _("reminder"), _MENU_("reminder text"), _HELP_("reminder text"), wxITEM_CHECK);
}
// in a spelling error? => show suggestions and "add to dictionary"
size_t error_pos = in_tag(val, _("<error-spelling"), selection_start_i, selection_start_i);
if (error_pos != String::npos) {
// TODO: "add to dictionary"
//%m.InsertSeparator(0);
//%m.Insert(0,ID_SPELLING_ADD_TO_DICT, _MENU_("add to dictionary"), _HELP_("add to dictionary"));
// suggestions
vector<String> suggestions;
get_spelling_suggestions(val, error_pos, suggestions);
// add suggestions to menu
m.InsertSeparator(0);
if (suggestions.empty()) {
m.Insert(0,ID_SPELLING_NO_SUGGEST, _MENU_("no spelling suggestions"), _HELP_("no spelling suggestions"));
} else {
int i = 0;
for(auto& s :suggestions) {
m.Insert(i, ID_SPELLING_SUGGEST + i, s, wxEmptyString);
i++;
}
}
}
// always show the menu
return true;
}
bool TextValueEditor::onCommand(int id) {
if (id >= ID_INSERT_SYMBOL_MENU_MIN && id <= ID_INSERT_SYMBOL_MENU_MAX) {
// Insert a symbol
if ((style().always_symbol || style().allow_formating) && style().symbol_font.valid()) {
String code = style().symbol_font.font->insertSymbolCode(id);
if (!style().always_symbol) {
code = _("<sym>") + code + _("</sym>");
}
replaceSelection(code, _ACTION_("insert symbol"));
return true;
}
} else if (id == ID_SPELLING_ADD_TO_DICT) {
// TODO
} else if (id >= ID_SPELLING_SUGGEST && id <= ID_SPELLING_SUGGEST_MAX) {
String val = value().value->toString();
size_t error_pos = in_tag(val, _("<error-spelling"), selection_start_i, selection_start_i);
if (error_pos == String::npos) throw InternalError(_("Unexpected spelling suggestion")); // wrong
// find the suggestions to pick from
vector<String> suggestions;
get_spelling_suggestions(val, error_pos, suggestions);
// select the error
selection_start_i = error_pos;
selection_end_i = match_close_tag(val, error_pos);
fixSelection(TYPE_INDEX);
// replace it
replaceSelection(suggestions.at(id - ID_SPELLING_SUGGEST), _ACTION_("correct"));
return true;
}
return false;
}
wxMenu* TextValueEditor::getMenu(int type) const {
if (type == ID_INSERT_SYMBOL && (style().always_symbol || style().allow_formating)
&& style().symbol_font.valid()) {
return style().symbol_font.font->insertSymbolMenu(viewer.getContext());
} else {
return nullptr;
}
}
// ----------------------------------------------------------------------------- : Drawing
void TextValueEditor::draw(RotatedDC& dc) {
if (nativeLook()) {
// clip the dc to the region of this control
dc.SetClippingRegion(style().getInternalRect());
}
// update scrollbar
prepareDrawScrollbar(dc);
// draw text
TextValueViewer::draw(dc);
// draw word list thingamajigies
drawWordListIndicators(dc);
// draw selection
if (isCurrent()) {
v.drawSelection(dc, style(), selection_start_i, selection_end_i);
// show caret, onAction() would be a better place
// but it has to be done after the viewer has updated the TextViewer
// we could do that ourselfs, but we need a dc for that
fixSelection();
showCaret();
}
if (nativeLook()) {
dc.DestroyClippingRegion();
}
}
void TextValueEditor::redrawSelection(size_t old_selection_start_i, size_t old_selection_end_i, bool old_drop_down_shown) {
// Hide caret
if (isCurrent()) {
wxCaret* caret = editor().GetCaret();
if (caret->IsVisible()) caret->Hide();
}
// Destroy the clientDC before reshowing the caret, prevent flicker on MSW
{
// Move selection
shared_ptr<RotatedDC> dcP = editor().overdrawDC();
RotatedDC& dc = *dcP;
Rotater r(dc, getRotation());
if (nativeLook()) {
// clip the dc to the region of this control
dc.SetClippingRegion(style().getInternalRect());
}
// clear old selection by drawing it again
if (!old_drop_down_shown) {
v.drawSelection(dc, style(), old_selection_start_i, old_selection_end_i);
}
// scroll?
scroll_with_cursor = true;
if (ensureCaretVisible()) {
// we can't redraw just the selection because we must scroll
updateScrollbar();
redraw();
} else {
// remove indicators
clearWordListIndicators(dc);
// draw new selection
if (!dropDownShown()) {
v.drawSelection(dc, style(), selection_start_i, selection_end_i);
}
// redraw drop down indicators
drawWordListIndicators(dc, true);
}
}
if (isCurrent()) {
showCaret();
}
}
// ----------------------------------------------------------------------------- : Other overrides
wxCursor rotated_ibeam;
wxCursor TextValueEditor::cursor(const RealPoint& pos) const {
WordListPosP p = findWordList(pos);
if (p) {
if (hovered_words != p.get()) {
hovered_words = p.get();
const_cast<TextValueEditor*>(this)->redrawWordListIndicators();
}
return wxCursor();
} else {
p = findWordListBody(pos);
if (hovered_words != p.get()) {
hovered_words = p.get();
const_cast<TextValueEditor*>(this)->redrawWordListIndicators();
}
Radians angle = viewer.getRotation().getAngle() + deg_to_rad(style().angle);
if (is_sideways(angle)) { // 90 or 270 degrees
if (!rotated_ibeam.Ok()) {
rotated_ibeam = wxCursor(load_resource_cursor(_("rot_text")));
}
return rotated_ibeam;
} else {
return wxCURSOR_IBEAM;
}
}
}
bool TextValueEditor::containsPoint(const RealPoint& pos) const {
RealPoint pos2(pos.x * style().getStretch(), pos.y);
if (TextValueViewer::containsPoint(pos2)) return true;
if (word_lists.empty()) return false;
return findWordList(pos) != nullptr;
}
RealRect TextValueEditor::boundingBox() const {
if (word_lists.empty()) return ValueViewer::boundingBox();
RealRect r = style().getInternalRect().grow(1);
for(const auto& wl : word_lists) {
r.width = max(r.width, wl->rect.right() + 9);
}
return r;
}
void TextValueEditor::onValueChange() {
TextValueViewer::onValueChange();
selection_start = selection_end = 0;
selection_start_i = selection_end_i = 0;
findWordLists();
}
void TextValueEditor::onAction(const Action& action, bool undone) {
TextValueViewer::onAction(action, undone);
findWordLists();
TYPE_CASE(action, TextValueAction) {
selection_start = action.selection_start;
selection_end = action.selection_end;
fixSelection(TYPE_CURSOR);
}
}
// ----------------------------------------------------------------------------- : Clipboard
bool TextValueEditor::canPaste() const {
return wxTheClipboard->IsSupported(wxDF_TEXT);
}
bool TextValueEditor::canCopy() const {
return selection_start != selection_end; // text is selected
}
bool TextValueEditor::doPaste() {
// get data
if (!wxTheClipboard->Open()) return false;
wxTextDataObject data;
bool ok = wxTheClipboard->GetData(data);
wxTheClipboard->Close();
if (!ok) return false;
// paste
replaceSelection(escape(data.GetText()), _ACTION_("paste"));
return true;
}
bool TextValueEditor::doCopy() {
// determine string to store
String val = value().value->toString();
if (selection_start_i > val.size()) selection_start_i = val.size();
if (selection_end_i > val.size()) selection_end_i = val.size();
size_t start = min(selection_start_i, selection_end_i);
size_t end = max(selection_start_i, selection_end_i);
String str = untag(val.substr(start, end - start));
if (str.empty()) return false; // no data to copy
// set data
if (!wxTheClipboard->Open()) return false;
bool ok = wxTheClipboard->SetData(new wxTextDataObject(str));
wxTheClipboard->Close();
return ok;
}
bool TextValueEditor::doDelete() {
replaceSelection(wxEmptyString, _ACTION_("cut"));
return true;
}
// ----------------------------------------------------------------------------- : Formatting
bool TextValueEditor::canFormat(int type) const {
const String& val = value().value->toString();
switch (type) {
case ID_FORMAT_BOLD: case ID_FORMAT_ITALIC:
return !style().always_symbol && style().allow_formating;
case ID_FORMAT_SYMBOL:
return !style().always_symbol && style().allow_formating && style().symbol_font.valid();
case ID_FORMAT_REMINDER:
return !style().always_symbol && style().allow_formating &&
is_in_tag(val, _("<kw"), selection_start_i, selection_start_i);
default:
return false;
}
}
bool TextValueEditor::hasFormat(int type) const {
const String& val = value().value->toString();
switch (type) {
case ID_FORMAT_BOLD:
return is_in_tag(val, _("<b"), selection_start_i, selection_end_i);
case ID_FORMAT_ITALIC:
return is_in_tag(val, _("<i"), selection_start_i, selection_end_i);
case ID_FORMAT_SYMBOL:
return is_in_tag(val, _("<sym"), selection_start_i, selection_end_i);
case ID_FORMAT_REMINDER: {
size_t tag = in_tag(val, _("<kw"), selection_start_i, selection_start_i);
if (tag != String::npos && tag + 4 < val.size()) {
Char c = val.GetChar(tag + 4);
return c == _('1') || c == _('A');
}
return false;
} default:
return false;
}
}
void TextValueEditor::doFormat(int type) {
size_t ss = selection_start, se = selection_end;
switch (type) {
case ID_FORMAT_BOLD: {
addAction(toggle_format_action(valueP(), _("b"), selection_start_i, selection_end_i, selection_start, selection_end, _("Bold")));
break;
}
case ID_FORMAT_ITALIC: {
addAction(toggle_format_action(valueP(), _("i"), selection_start_i, selection_end_i, selection_start, selection_end, _("Italic")));
break;
}
case ID_FORMAT_SYMBOL: {
addAction(toggle_format_action(valueP(), _("sym"), selection_start_i, selection_end_i, selection_start, selection_end, _("Symbols")));
break;
}
case ID_FORMAT_REMINDER: {
addAction(new TextToggleReminderAction(valueP(), selection_start_i));
break;
}
}
selection_start = ss;
selection_end = se;
fixSelection();
}
// ----------------------------------------------------------------------------- : Selection
void TextValueEditor::showCaret() {
if (dropDownShown()) {
wxCaret* caret = editor().GetCaret();
if (caret && caret->IsVisible()) caret->Hide();
return;
}
// Rotation
Rotation rot(viewer.getRotation());
Rotater rot2(rot, getRotation());
// The caret
wxCaret* caret = editor().GetCaret();
// cursor rectangle
RealRect cursor = v.charRect(selection_end_i, selection_start_i <= selection_end_i);
cursor.width = 0;
// height may be 0 near a <line>
// it is not 0 for empty text, because TextRenderer handles that case
if (cursor.height == 0) {
if (style().always_symbol && style().symbol_font.valid()) {
style().symbol_font.font->update(viewer.getContext());
RealSize s = style().symbol_font.font->defaultSymbolSize(rot.trS(style().symbol_font.size));
cursor.height = s.height;
} else {
cursor.height = v.heightOfLastLine();
if (cursor.height == 0) {
wxClientDC dc(&editor());
// TODO : high quality?
dc.SetFont(style().font.toWxFont(1.0));
int hi;
dc.GetTextExtent(_(" "), 0, &hi);
#ifdef __WXGTK__
// HACK: Some fonts don't get the descender height set correctly.
int charHeight = dc.GetCharHeight();
if (charHeight != hi)
hi += hi - charHeight;
#endif
cursor.height = rot.trS(hi);
}
}
}
// clip caret pos and size; show caret
if (nativeLook()) {
if (cursor.y + cursor.height <= 0 || cursor.y >= style().height) {
// caret should be hidden
if (caret->IsVisible()) caret->Hide();
return;
} else if (cursor.y < 0) {
// caret partially hidden, clip
cursor.height -= -cursor.y;
cursor.y = 0;
} else if (cursor.y + cursor.height >= style().height) {
// caret partially hidden, clip
cursor.height = style().height - cursor.y;
}
}
// rotate
// TODO: handle rotated cursor
cursor = rot.trRectToBB(cursor);
// set size
wxSize size = cursor.size();
if (size.GetWidth() == 0) size.SetWidth (1);
if (size.GetHeight() == 0) size.SetHeight(1);
// resize, move, show
if (size != caret->GetSize()) {
caret->SetSize(size);
}
caret->Move(cursor.position());
if (!caret->IsVisible()) caret->Show();
}
void TextValueEditor::insert(const String& text, const String& action_name) {
replaceSelection(text, action_name);
}
/// compare two cursor positions, determine how much the text matches before and after
size_t match_cursor_position(size_t pos1, const String& text1, size_t pos2, const String& text2) {
pos1 = min(pos1, text1.size());
pos2 = min(pos2, text2.size());
size_t score = 0; // total score
// Match part before cursor
size_t before1, before2;
for (before1 = before2 = 0 ; before1 < pos1 && before2 < pos2 ; ++before1, ++before2) {
Char c1 = text1.GetChar(pos1-before1-1), c2 = text2.GetChar(pos2-before2-1);
if (c1 == c2) score += 10000;
else if (toLower(c1) == toLower(c2)) score += 9999;
else if (isPunct(c1) && isPunct(c2)) score += 1;
else if (c1 == UNTAG_ATOM_KWPPH) {score += 1; --before2;}
else break;
}
// bonus points for matching start of string
if (pos1 == before1 && pos2 == before2) score += 10000;
// Match part after cursor
size_t after1, after2;
for (after1 = after2 = 0 ; pos1 + after1 < text1.size() && pos2 + after2 < text2.size() ; ++after1, ++after2) {
Char c1 = text1.GetChar(pos1+after1), c2 = text2.GetChar(pos2+after2);
if (c1 == c2) score += 10;
else if (toLower(c1) == toLower(c2)) score += 9;
else if (isPunct(c1) && isPunct(c2)) score += 1;
else if (c2 == UNTAG_ATOM_KWPPH) {score += 1; --after1;}
else break;
}
// bonus points for matching end of string
if (pos1+after1 == text1.size() && pos2+after2 == text2.size()) score += 2;
// final score: matching 'before' is more important
return score;
}
void TextValueEditor::replaceSelection(const String& replacement, const String& name, bool allow_auto_replace, bool select_on_undo) {
if (replacement.empty() && selection_start == selection_end) {
// no text selected, nothing to delete
return;
}
// fix the selection, it may be changed by undo/redo
if (selection_end < selection_start) swap(selection_end, selection_start);
fixSelection();
// execute the action before adding it to the stack,
// because we want to run scripts before action listeners see the action
TextValueAction* action = typing_action(valueP(), selection_start_i, selection_end_i, select_on_undo ? selection_start : selection_end, selection_end, replacement, name);
if (!action) {
// nothing changes, but move the selection anyway
moveSelection(TYPE_CURSOR, selection_end);
return;
}
// what we would expect if no scripts take place
String expected_value = untag_for_cursor(action->newValue());