-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
FMX.Memo.Style3.pas
3877 lines (3558 loc) · 120 KB
/
FMX.Memo.Style3.pas
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
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2023 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Memo.Style;
interface
{$SCOPEDENUMS ON}
uses
System.Types, System.Classes, System.UITypes, System.Generics.Collections,
FMX.Platform, FMX.Memo, FMX.Graphics, FMX.Types, FMX.Controls, FMX.TextLayout,
FMX.Objects, FMX.MagnifierGlass, FMX.SpellChecker, FMX.Menus, FMX.Text,
FMX.Presentation.Messages, FMX.Presentation.Style, FMX.Controls.Presentation,
FMX.ScrollBox.Style, FMX.Memo.Types, FMX.Controls.Model;
type
///<summary>Record that describes text-editing operation</summary>
TEditAction = record
///<summary>Type of change that was made (text added or removed)</summary>
ActionType: TActionType;
///<summary>Defines that change was made right after the previous and was made in the similar way
///(e.g. text editing (delete and insert) via keyabord)</summary>
PairedWithPrev: Boolean;
///<summary>Position in text from which text was deleted or into which text was inserted</summary>
StartPosition: Integer;
///<summary>Fragmen of text that was deleted (for TActionType.Delete only)</summary>
DeletedFragment: string;
///<summary>Length of text that was inserted (for <c>TActionType.Insert</c> only)</summary>
Length: Integer;
///<summary>Was text inserted via typing from keyboard or not</summary>
Typed: Boolean;
///<summary>Was removed text select or not</summary>
WasSelected: Boolean;
///<summary>Was caret moved after text was removed or not</summary>
CaretMoved: Boolean;
end;
TStyledMemo = class;
{ TEditActionStack }
///<summary>List of text-editing operations</summary>
TEditActionStack = class(TStack<TEditAction>)
private
[Weak]
FOwner: TStyledMemo;
public
constructor Create(const AOwner: TStyledMemo);
///<summary>New fragment of text was inserted</summary>
procedure FragmentInserted(const StartPos, FragmentLength: Integer; const PairedWithPrev, Typed: Boolean);
///<summary>Some text fragment was removed</summary>
procedure FragmentDeleted(const StartPos: Integer; const Fragment: string; const Selected, CaretMoved: Boolean);
///<summary>Revert last change</summary>
function RollBackAction: Boolean;
end;
TOnUpdateLayoutParams = procedure(Sender: TObject; Layout: TTextLayout; const Index: Integer) of object;
{ TStyledMemo }
///<summary>Styled presentation for <c>TMemo</c></summary>
TStyledMemo = class(TStyledCustomScrollBox, ITextInput, ITextSpellCheck, ITextSpellCheckActions)
protected
type
///<summary>Class that represents single rendering line</summary>
TLineObject = class
private
FSize: TSizeF;
FLayout: TTextLayout;
FRect: TRectF;
public
///<summary>Free text layout object if it exists</summary>
procedure FreeLayout;
///<summary>Does layout line has valid size</summary>
function SizeValid: Boolean;
///<summary>Reset current size and line rectangle if line parameters were changed</summary>
procedure InvalidateSize;
constructor Create; overload;
constructor Create(const ALayout: TTextLayout; const ASize: TSizeF); overload;
destructor Destroy; override;
//
property Size: TSizeF read FSize write FSize;
property Rect: TRectF read FRect write FRect;
property Layout: TTextLayout read FLayout write FLayout;
end;
///<summary>Providing a bridge between lines of text in TMemo.Model.Lines and the internal representation</summary>
TLines = class
private
[Weak]
FMemo: TStyledMemo;
FLines: TObjectList<TLineObject>;
FTopLine: Integer;
FDefaultHeight: Single;
FUpdating: Integer;
FNewContentBounds: TRectF;
FNeedUpdateContentSize: Boolean;
FOnUpdateLayoutParams: TOnUpdateLayoutParams;
function CreateLayout(const S: string; const Index: Integer): TTextLayout;
function IsWordWrap: Boolean;
procedure UpdateLayoutParams(Layout: TTextLayout; const Index: Integer);
procedure UpdateLayoutsColor;
procedure CalculateDefaultLineMetrics;
function GetDefaultLineHeight: Single;
function GetCount: Integer;
function GetItem(const Index: Integer): TLineObject;
procedure UpdateContentBounds(ContentBounds: TRectF);
public
constructor Create(Memo: TStyledMemo);
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function IsUpdating: Boolean;
procedure InsertLine(const Index: Integer; const S: string);
procedure DeleteLine(const Index: Integer);
procedure ReplaceLine(const Index: Integer; const S: string);
procedure ExchangeLines(const OldIndex, NewIndex: Integer);
//Caret support
///<summary>Get line number and position in line by the point coordinates</summary>
function GetPointPosition(const Pt: TPointF; const RoundToWord: Boolean = False): TCaretPosition;
///<summary>Get the coordinates on the region that holds range of text starting from defined line, position in
///that line and the defined length.</summary>
function GetRegionForRange(const ALine, APos, ALength: Integer; const RoundToWord: Boolean = False): TRegion;
//
procedure RenderLayouts;
//
property Count: Integer read GetCount;
property Items[const Index: Integer]: TLineObject read GetItem; default;
end;
///<summary>Inforation about a single misspelled word in the text</summary>
TSpellingWord = class
private
FPosition: TCaretPosition;
FLength: Integer;
FBounds: TRegion;
public
constructor Create(const APosition: TCaretPosition; const ALength: Integer; const ABounds: TRegion);
function HasBounds: Boolean;
function PosAtCurrentPos(const APosition: TCaretPosition): Boolean;
procedure InvalidateBounds;
property Position: TCaretPosition read FPosition write FPosition;
property Length: Integer read FLength write FLength;
property Bounds: TRegion read FBounds write FBounds;
end;
private
FTextService: TTextService;
FLMouseSelecting: Boolean;
FIgnoreMouseMove: Boolean;
FDownMPt: TPointF;
FOldMPt: TPointF;
FCaretPosition: TCaretPosition;
FMemoPopupMenu: TPopupMenu;
FActionStack: TEditActionStack;
FLineObjects: TLines;
FSelStart: TCaretPosition;
FSelEnd: TCaretPosition;
FSelected: Boolean;
FCursorFill: TBrush;
FContent: TControl;
FStartAutoScrollTimer: TTimer;
FAutoVScrollTimer: TTimer;
FAutoHScrollTimer: TTimer;
FNeedAutoVScroll: Boolean;
FNeedAutoHScroll: Boolean;
FFollowTheMouse: Boolean;
FCharsBuffer: string;
{ Selection }
FLeftSelPt: TSelectionPoint;
FRightSelPt: TSelectionPoint;
{ Loupe }
FLoupeService: ILoupeService;
{ ITextSettings }
FLineHeight: Single;
FSetFocusOnUp: Boolean;
FOldWordWrap: Boolean;
{ Spelling }
FSpellService: IFMXSpellCheckerService;
FSpellMenuItems: TList<TMenuItem>;
FSpellHightlightRect: TRectF;
FSpellFill: TBrush;
FSpellUnderlineBrush: TStrokeBrush;
FSpellingWords: TObjectList<TSpellingWord>;
FOnUpdateLayoutParams: TOnUpdateLayoutParams;
FNeedSelectorPoints: Boolean;
FScrollToCaret: Boolean;
FLinesBackgroundColor: TDictionary<Integer, TAlphaColor>;
function GetModel: TCustomMemoModel;
function GetMemo: TCustomMemo;
function GetPageSize: Single;
procedure SetCaretPosition(const Value: TCaretPosition);
function GetNextWordBegin(const StartPosition: TCaretPosition): TCaretPosition;
function GetPrevWordBegin(const StartPosition: TCaretPosition): TCaretPosition;
function GetPositionShift(const APos: TCaretPosition; const Delta: Integer): TCaretPosition;
{ Selection }
function GetSelBeg: TCaretPosition;
function GetSelEnd: TCaretPosition;
procedure SelPtMouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure LeftSelPtChangePositionHandler(Sender: TObject; var X, Y: Single);
procedure LeftSelPtMouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure RightSelPtChangePositionHandler(Sender: TObject; var X, Y: Single);
procedure RightSelPtMouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
{ Check spelling }
procedure FindSpellingErrorsInLine(const LineIndex: Integer);
procedure RemoveSpellingErrorsForLine(const LineIndex: Integer);
procedure DoScroll(const ADirection: Integer);
{ Loupe }
procedure HideLoupe;
procedure ShowLoupe;
procedure SetLoupePosition(const ASelectionPointType: TSelectionPointType); overload;
procedure SetLoupePosition(const X, Y: Single); overload;
// Selection Autoscroll
procedure StartAutoScroll(const X, Y: Single);
procedure StopAutoScroll;
procedure StartAutoScrollHandler(Sender: TObject);
procedure AutoScrollUpHandler(Sender: TObject);
procedure AutoScrollDownHandler(Sender: TObject);
procedure AutoScrollLeftHandler(Sender: TObject);
procedure AutoScrollRightHandler(Sender: TObject);
{ Spelling }
procedure UpdateSpellPopupMenu(const APoint: TPointF);
procedure SpellFixContextMenuHandler(Sender: TObject);
procedure SetOnUpdateLayoutParams(const Value: TOnUpdateLayoutParams);
procedure SetNeedSelectorPoints(const Value: Boolean);
procedure SetScrollToCaret(const Value: Boolean);
procedure UpdateLinesPos;
protected
FDisableCaretInsideWords: Boolean;
{ Messages from model }
procedure MMCharCaseChanged(var Message: TDispatchMessageWithValue<TEditCharCase>); message MM_MEMO_CHARCASE_CHANGED;
procedure MMCheckSpellingChanged(var Message: TDispatchMessageWithValue<Boolean>); message MM_MEMO_CHECKSPELLING_CHANGED;
procedure MMHideSelectionOnExitChanged(var Message: TDispatchMessageWithValue<Boolean>); message MM_MEMO_HIDESELECTIONONEXIT_CHANGED;
procedure MMReadOnlyChanged(var Message: TDispatchMessageWithValue<Boolean>); message MM_MEMO_READONLY_CHANGED;
procedure MMImeModeChanged(var Message: TDispatchMessageWithValue<TImeMode>); message MM_MEMO_IMEMODE_CHANGED;
procedure MMSetSelStart(var Message: TDispatchMessageWithValue<Integer>); message MM_MEMO_SELSTART_CHANGED;
procedure MMSelLengthChanged(var Message: TDispatchMessageWithValue<Integer>); message MM_MEMO_SELLENGTH_CHANGED;
procedure MMTextSettingsChanged(var Message: TDispatchMessage); message MM_MEMO_TEXT_SETTINGS_CHANGED;
procedure MMLinesInsertLine(var Message: TDispatchMessageWithValue<TCustomMemoModel.TLineInfo>); message MM_MEMO_LINES_INSERT_LINE;
procedure MMLinesPutLine(var Message: TDispatchMessageWithValue<TCustomMemoModel.TLineInfo>); message MM_MEMO_LINES_PUT_LINE;
procedure MMLinesDeleteLine(var Message: TDispatchMessageWithValue<TCustomMemoModel.TLineInfo>); message MM_MEMO_LINES_DELETE_LINE;
procedure MMLinesExchangeLines(var Message: TDispatchMessageWithValue<TCustomMemoModel.TLineInfo>); message MM_MEMO_LINES_EXCHANGE_LINES;
procedure MMLinesClear(var Message: TDispatchMessage); message MM_MEMO_LINES_CLEAR;
procedure MMUpdateStateChanged(var Message: TDispatchMessageWithValue<Boolean>); message MM_MEMO_UPDATE_STATE_CHANGED;
procedure MMGetCaretPosition(var Message: TDispatchMessageWithValue<TCaretPosition>); message MM_MEMO_GET_CARET_POSITION;
procedure MMSetCaretPosition(var Message: TDispatchMessageWithValue<TCaretPosition>); message MM_MEMO_SET_CARET_POSITION;
procedure MMCanSetFocus(var Message: TDispatchMessageWithValue<Boolean>); message MM_MEMO_CAN_SET_FOCUS;
procedure MMLinesChanged(var Message: TDispatchMessage); message MM_MEMO_LINES_CHANGED;
procedure MMMaxLengthChanged(var Message: TDispatchMessage); message MM_MEMO_MAXLENGTH_CHANGED;
procedure MMGetCaretPositionByPoint(var Message: TDispatchMessageWithValue<TCustomMemoModel.TGetCaretPositionInfo>); message MM_MEMO_GET_CARET_POSITION_BY_POINT;
{ Messages from presented control }
procedure PMInit(var Message: TDispatchMessage); message PM_INIT;
procedure PMGotoLineBegin(var Message: TDispatchMessage); message PM_MEMO_GOTO_LINE_BEGIN;
procedure PMGotoLineEnd(var Message: TDispatchMessage); message PM_MEMO_GOTO_LINE_END;
procedure PMFragmentInserted(var Message: TDispatchMessageWithValue<TFragmentInserted>); message PM_MEMO_UNDO_MANAGER_INSERT_TEXT;
procedure PMFragmentDeleted(var Message: TDispatchMessageWithValue<TFragmentDeleted>); message PM_MEMO_UNDO_MANAGER_DELETE_TEXT;
procedure PMUndo(var Message: TDispatchMessage); message PM_MEMO_UNDO_MANAGER_UNDO;
procedure PMSelectText(var Message: TDispatchMessage); message PM_MEMO_SELECT_TEXT;
procedure DoEndUpdate; override;
procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); virtual;
//Animation mouse events
procedure AniMouseDown(const Touch: Boolean; const X, Y: Single); override;
procedure AniMouseMove(const Touch: Boolean; const X, Y: Single); override;
procedure AniMouseUp(const Touch: Boolean; const X, Y: Single); override;
///<summary>Returns default line height according to current text decoration settings</summary>
function GetLineHeight: Single;
///<summary>Creates popup menu items</summary>
procedure CreatePopupMenu; virtual;
///<summary>Updates the current state of popup menu items</summary>
procedure UpdatePopupMenuItems; virtual;
procedure ApplyStyle; override;
procedure FreeStyle; override;
procedure Resize; override;
///<summary>Raises OnChange event</summary>
procedure DoChange; virtual;
///<summary>Revert last text change</summary>
procedure DoUndo(Sender: TObject);
///<summary>Cut selected text to the clipboard</summary>
procedure DoCut(Sender: TObject);
///<summary>Copy selected text to the clipboard</summary>
procedure DoCopy(Sender: TObject);
///<summary>Paste text from clipboard to the current caret position</summary>
procedure DoPaste(Sender: TObject);
///<summary>Delete selected text</summary>
procedure DoDelete(Sender: TObject);
///<summary>Select all text</summary>
procedure DoSelectAll(Sender: TObject);
///<summary>Repainting content in memo</summary>
procedure RepaintEdit;
{ inherited }
function ShowContextMenu(const ScreenPosition: TPointF): Boolean; override;
procedure DoViewportPositionChange(const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: boolean); override;
procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
/// <summary>Defines <c>TMemo</c> model class</summary>
function DefineModelClass: TDataModelClass; override;
{ ITouchEvents }
///<summary>Long tap</summary>
procedure LongTap(const X, Y: Single);
///<summary>Double tap</summary>
procedure DblTap;
procedure CMGesture(var EventInfo: TGestureEventInfo); override;
{ Selection }
procedure UpdateSelectionInModel; virtual;
function GetShowSelection: Boolean; virtual;
procedure BeginSelection;
procedure EndSelection;
procedure GetNormalizedSelectionRange(var ASelStart, ASelEnd: TCaretPosition);
procedure SetNormalizedSelectionRange(const ASelStart, ASelEnd: TCaretPosition);
function GetSelectionRegion: TRegion;
function HaveSelectionPickers: Boolean;
procedure UpdateSelectionPointPositions;
{ Caret }
procedure PutCaretTo(const X, Y: Single; const Select: Boolean = False; const PositionByWord: Boolean = False);
procedure SelectAtPos(const APos: TCaretPosition);
procedure UpdateCaretPosition(const UpdateScrllBars: Boolean);
procedure UpdateHScrlBarByCaretPos;
procedure UpdateVScrlBarByCaretPos;
{ ITextSpellCheck }
function IsSpellCheckEnabled: Boolean;
function IsCurrentWordWrong: Boolean;
function GetListOfPrepositions: TArray<string>;
procedure HighlightSpell;
procedure HideHighlightSpell;
{ ITextSpellCheckActions }
procedure Spell(const AWord: string);
{ ITextInput }
function GetTextService: TTextService;
function GetTargetClausePointF: TPointF;
procedure StartIMEInput;
procedure EndIMEInput;
procedure IMEStateUpdated;
function GetSelection: string;
function GetSelectionRect: TRectF;
function GetSelectionBounds: TRect;
function GetSelectionPointSize: TSizeF;
function HasText: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RecalcOpacity; override;
{ Caret }
procedure MoveCaretBy(const Delta: Integer);
procedure MoveCaretLeft;
procedure MoveCaretRight;
procedure MoveCaretVertical(const LineDelta: Integer);
procedure MoveCaretDown;
procedure MoveCaretUp;
procedure MoveCaretPageUp;
procedure MoveCaretPageDown;
function GetPositionPoint(const ACaretPos: TCaretPosition): TPointF;
procedure GotoLineBegin;
procedure GotoLineEnd;
procedure GotoTextBegin;
procedure GotoTextEnd;
property Memo: TCustomMemo read GetMemo;
///<summary>Component data model</summary>
property Model: TCustomMemoModel read GetModel;
///<summary>Current caret position in text</summary>
property CaretPosition: TCaretPosition read FCaretPosition write SetCaretPosition;
property DisableCaretInsideWords: Boolean read FDisableCaretInsideWords write FDisableCaretInsideWords;
property LineHeight: Single read GetLineHeight;
property SelBeg: TCaretPosition read GetSelBeg;
property SelEnd: TCaretPosition read GetSelEnd;
property PageSize: Single read GetPageSize;
///
property LineObjects: TLines read FLineObjects;
property OnUpdateLayoutParams: TOnUpdateLayoutParams read FOnUpdateLayoutParams write SetOnUpdateLayoutParams;
property NeedSelectorPoints: Boolean read FNeedSelectorPoints write SetNeedSelectorPoints;
property ScrollToCaret: Boolean read FScrollToCaret write SetScrollToCaret;
function GetWordAtPos(const X, Y: Single; out BeginWord, Line: Int64): string;
procedure UpdateVisibleLayoutParams; overload;
procedure UpdateVisibleLayoutParams(const Index: Integer); overload;
property LinesBackgroundColor: TDictionary<Integer, TAlphaColor> read FLinesBackgroundColor;
end;
implementation
uses
System.SysUtils, System.RTLConsts, System.Variants, FMX.Consts, System.Math,
System.UIConsts, System.Character, System.TypInfo, System.Math.Vectors,
FMX.Presentation.Factory, System.SyncObjs, FMX.Clipboard;
const
LOUPE_OFFSET = 10;
cnTouchAccuracy = 3;
IMEWindowGap = 2; // 2 is small space between conrol and IME window
CutStyleName = 'cut'; //Do not localize
UndoStyleName = 'undo'; //Do not localize
CopyStyleName = 'copy'; //Do not localize
PasteStyleName = 'paste'; //Do not localize
DeleteStyleName = 'delete'; //Do not localize
SelectAllStyleName = 'selectall'; //Do not localize
ContentStyleResourceName = 'content'; //Do not localize
SelectionStyleResourceName = 'selection'; //Do not localize
ForegroundStyleResourceName = 'foreground'; //Do not localize
FontStyleResourceName = 'font'; //Do not localize
CaretColorStyleResouceName = 'caretcolor'; //Do not localize
LeftSelectionPointStyleResourceName = 'leftselectionpoint'; //Do not localize
RightSelectionPointStyleResourceName = 'rightselectionpoint'; //Do not localize
{$IFDEF ANDROID}
function TextToLines(const Text: string): TStrings;
var
LText: string;
begin
Result := TStringList.Create;
LText := Text;
if LText.EndsWith(Result.LineBreak) and not LText.IsEmpty then
LText := LText + Result.LineBreak;
Result.Text := LText;
end;
{$ENDIF}
function RectsIntersect(const R1, R2: TRectF): Boolean;
begin
Result := (R1.Left <= R2.Right) and (R1.Right >= R2.Left) and (R1.Top <= R2.Bottom) and (R1.Bottom >= R2.Top);
end;
type
TStyledMemoHelper = class helper for TStyledMemo
procedure SelectionPointGestureHandler(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);
end;
{ TStyledMemoHelper }
procedure TStyledMemoHelper.SelectionPointGestureHandler(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
Handled := EventInfo.GestureID = igiPan;
end;
{ TStyledMemo }
function TStyledMemo.GetMemo: TCustomMemo;
begin
Result := PresentedControl as TCustomMemo;
end;
function TStyledMemo.GetModel: TCustomMemoModel;
begin
Result := inherited GetModel<TCustomMemoModel>;
end;
constructor TStyledMemo.Create(AOwner: TComponent);
var
PlatformTextService: IFMXTextService;
PlatformTextEditingBehaviorService: IFMXTextEditingService;
begin
inherited;
FLinesBackgroundColor := TDictionary<integer, TAlphaColor>.Create;
EnableExecuteAction := False;
if TPlatformServices.Current.SupportsPlatformService(IFMXTextService, PlatformTextService) then
FTextService := PlatformTextService.GetTextServiceClass.Create(Self, True)
else
FTextService := nil;
if not TPlatformServices.Current.SupportsPlatformService(ILoupeService, FLoupeService) then
FLoupeService := nil;
FLineObjects := TLines.Create(Self);
CreatePopupMenu;
FActionStack := TEditActionStack.Create(Self);
FLMouseSelecting := False;
FOldMPt := TPointF.Zero;
FCaretPosition := TCaretPosition.Zero;
if FTextService <> nil then
FTextService.ImeMode := TImeMode.imDontCare;
FSelStart := TCaretPosition.Zero;
FSelEnd := TCaretPosition.Zero;
FSelected := False;
FScrollToCaret := True;
CanFocus := False;
AutoCapture := True;
SetAcceptsControls(False);
//Timer to start scrolling when selecting text and cursor is out of content
FStartAutoScrollTimer := TTimer.Create(Self);
FStartAutoScrollTimer.Enabled := False;
FStartAutoScrollTimer.Interval := 300;
FStartAutoScrollTimer.OnTimer := StartAutoScrollHandler;
FAutoVScrollTimer := TTimer.Create(Self);
FAutoVScrollTimer.Interval := 50;
FAutoVScrollTimer.Enabled := False;
FAutoHScrollTimer := TTimer.Create(Self);
FAutoHScrollTimer.Interval := 50;
FAutoHScrollTimer.Enabled := False;
Touch.InteractiveGestures := Touch.InteractiveGestures + [TInteractiveGesture.DoubleTap, TInteractiveGesture.LongTap];
FSpellMenuItems := TList<TMenuItem>.Create;
FSpellFill := TBrush.Create(TBrushKind.Solid, TAlphaColorRec.Red);
FSpellUnderlineBrush := TStrokeBrush.Create(TBrushKind.Solid, TAlphaColorRec.Red);
FSpellUnderlineBrush.Dash := TStrokeDash.Dot;
FSpellUnderlineBrush.Thickness := 1;
FSpellingWords := TObjectList<TSpellingWord>.Create;
if TPlatformServices.Current.SupportsPlatformService(IFMXTextEditingService, PlatformTextEditingBehaviorService) then
begin
FDisableCaretInsideWords := TCaretBehavior.DisableCaretInsideWords in PlatformTextEditingBehaviorService.GetCaretBehaviors;
PlatformTextEditingBehaviorService := nil;
end
else
FDisableCaretInsideWords := False;
Width := 100;
end;
function TStyledMemo.DefineModelClass: TDataModelClass;
begin
Result := TCustomMemoModel;
end;
destructor TStyledMemo.Destroy;
begin
FLoupeService := nil;
FCursorFill.Free;
FActionStack.Free;
FMemoPopupMenu.Free;
FLineObjects.Free;
FTextService.Free;
FSpellService := nil;
FSpellMenuItems.Free;
FSpellingWords.Free;
FSpellFill.Free;
FSpellUnderlineBrush.Free;
FLinesBackgroundColor.Free;
inherited;
end;
procedure TStyledMemo.HideHighlightSpell;
begin
FSpellHightlightRect := TRectF.Empty;
Model.Caret.TemporarilyHidden := FSelected and (Model.SelLength > 0) and IsFocused;
RepaintEdit;
end;
procedure TStyledMemo.DoEndUpdate;
function IsLoading: Boolean;
begin
Result := csLoading in PresentedControl.ComponentState;
end;
function IsDestroying: Boolean;
begin
Result := csDestroying in PresentedControl.ComponentState;
end;
procedure RecalculateContextBounds;
begin
if not FLineObjects.IsUpdating and FLineObjects.FNeedUpdateContentSize then
FLineObjects.UpdateContentBounds(FLineObjects.FNewContentBounds);
end;
begin
inherited;
if not (IsUpdating or IsLoading or IsDestroying) then
begin
RecalculateContextBounds;
FLineObjects.RenderLayouts;
UpdateLinesPos;
CaretPosition := TCaretPosition.Create(EnsureRange(CaretPosition.Line, -1, Model.Lines.Count - 1), CaretPosition.Pos);
UpdateCaretPosition(True);
RepaintEdit;
end;
end;
procedure TStyledMemo.DoEnter;
{$IFDEF MSWINDOWS}
var
MouseService: IFMXMouseService;
MousePos: TPointF;
ContentRect: TRectF;
LCaretPosition: TCaretPosition;
{$ENDIF}
begin
inherited;
if Model.Lines.Count > 0 then
begin
FCaretPosition.Line := EnsureRange(FCaretPosition.Line, 0, Model.Lines.Count - 1);
FCaretPosition.Pos := EnsureRange(FCaretPosition.Pos, 0, Model.Lines[FCaretPosition.Line].Length);
end
else
FCaretPosition := TCaretPosition.Zero;
{$IFNDEF ANDROID}
if not FTextService.HasMarkedText then
begin
if Model.Lines.Count > 0 then
FTextService.Text := Model.Lines[FCaretPosition.Line]
else
FTextService.Text := string.Empty;
end;
{$IFDEF MSWINDOWS}
if FTextService.HasMarkedText and TPlatformServices.Current.SupportsPlatformService(IFMXMouseService, MouseService) then
try
MousePos := ScreenToLocal(MouseService.GetMousePos);
ContentRect := Model.ContentBounds;
MousePos.X := EnsureRange(MousePos.X, ContentRect.Left, ContentRect.Right);
MousePos.Y := EnsureRange(MousePos.Y, ContentRect.Top, ContentRect.Bottom);
MousePos.Offset(-ContentRect.TopLeft);
LCaretPosition := FLineObjects.GetPointPosition(MousePos, False);
FTextService.CaretPosition := TPoint.Create(LCaretPosition.Pos, LCaretPosition.Line);
IMEStateUpdated;
finally
MouseService := nil;
end;
{$ENDIF}
{$ELSE}
FTextService.Text := Model.Lines.Text;
{$ENDIF}
UpdateCaretPosition(False);
if Model.AutoSelect and not FTextService.HasMarkedText then
Memo.SelectAll;
end;
procedure TStyledMemo.DoExit;
begin
DoChange;
if Observers.IsObserving(TObserverMapping.EditLinkID) then
TLinkObservers.EditLinkUpdate(Observers);
if Observers.IsObserving(TObserverMapping.ControlValueID) then
TLinkObservers.ControlValueUpdate(Observers);
inherited;
UpdateSelectionPointPositions;
end;
procedure TStyledMemo.GotoLineBegin;
var
Point: TPointF;
begin
if Model.Lines.Count > 0 then
begin
Point := TPointF.Create(-ViewportPosition.X, Model.Caret.Pos.Y - ViewportPosition.Y +
GetLineHeight / 2);
CaretPosition := FLineObjects.GetPointPosition(Point);
end;
end;
procedure TStyledMemo.GotoLineEnd;
var
ContentRect: TRectF;
Point: TPointF;
begin
if Model.Lines.Count > 0 then
begin
ContentRect := TRectF.Create(0, 0, Model.ViewportSize.Width, Model.ViewportSize.Height);
if (CaretPosition.Line >= FLineObjects.Count) or
not RectsIntersect(ContentRect, FLineObjects[CaretPosition.Line].Rect) then
begin
FLineObjects.RenderLayouts;
UpdateCaretPosition(True);
end;
Point := TPointF.Create(FLineObjects[CaretPosition.Line].Rect.Right - 1,
Model.Caret.Pos.Y - ViewportPosition.Y + GetLineHeight / 2);
CaretPosition := FLineObjects.GetPointPosition(Point);
end;
end;
procedure TStyledMemo.GotoTextBegin;
begin
FCaretPosition := TCaretPosition.Zero;
FSelected := False;
UpdateSelectionInModel;
UpdateCaretPosition(True);
end;
procedure TStyledMemo.GotoTextEnd;
begin
if Model.Lines.Count = 0 then
FCaretPosition := TCaretPosition.Zero
else
FCaretPosition := TCaretPosition.Create(Model.Lines.Count - 1, Model.Lines[Model.Lines.Count - 1].Length);
FSelected := False;
UpdateSelectionInModel;
UpdateCaretPosition(True);
end;
function TStyledMemo.GetPositionPoint(const ACaretPos: TCaretPosition): TPointF;
var
Region: TRegion;
LineRect: TRectF;
Line: TLineObject;
begin
Region := FLineObjects.GetRegionForRange(ACaretPos.Line, ACaretPos.Pos, 1);
if Length(Region) > 0 then
begin
Line := FLineObjects[ACaretPos.Line];
LineRect := FLineObjects[ACaretPos.Line].Rect;
if Line.SizeValid then
Result := TPointF.Create(
EnsureRange(Region[0].Left, LineRect.Left, LineRect.Right),
EnsureRange(Region[0].Top, LineRect.Top, LineRect.Bottom))
else
Result := Region[0].Topleft;
Result.Offset(ViewportPosition);
end
else
Result := TPointF.Zero;
end;
procedure TStyledMemo.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
var
TmpS: string;
OldCaretPosition, LCaret: TCaretPosition;
WasSelection, IsCtrlOrCmd: Boolean;
LTmpOptions: TInsertOptions;
KeyHandled: Boolean;
begin
KeyHandled := False;
if Observers.IsObserving(TObserverMapping.EditLinkID) then
begin
if (Key = vkReturn) or (Key = vkBack) or (Key = vkDelete) or ((Key = vkInsert) and (ssShift in Shift)) then
if TLinkObservers.EditLinkEdit(Observers) then
TLinkObservers.EditLinkModified(Observers)
else
begin
TLinkObservers.EditLinkReset(Observers);
Exit;
end;
if (KeyChar >= #32) and not TLinkObservers.EditLinkIsValidChar(Observers, KeyChar) then
begin
KeyChar := #0;
Exit;
end;
case KeyChar of
^H, ^V, ^X, #32..High(Char):
if not TLinkObservers.EditLinkEdit(Observers) then
begin
KeyChar := #0;
TLinkObservers.EditLinkReset(Observers);
Exit;
end
else
TLinkObservers.EditLinkModified(Observers);
#27:
begin
TLinkObservers.EditLinkReset(Observers);
Memo.SelectAll;
KeyChar := #0;
Exit;
end;
end;
end;
if Observers.IsObserving(TObserverMapping.ControlValueID) and (KeyChar <> #0) then
TLinkObservers.ControlValueModified(Observers);
inherited KeyDown(Key, KeyChar, Shift);
OldCaretPosition := CaretPosition;
if (Key = vkReturn) and not (ssCommand in Shift) and not Model.ReadOnly then
begin
WasSelection := Model.SelLength > 0;
if WasSelection then
Model.DeleteFrom(GetSelBeg, Model.SelLength, [TDeleteOption.MoveCaret, TDeleteOption.CanUndo,
TDeleteOption.Selected]);
if WasSelection then
LTmpOptions := [TInsertOption.UndoPairedWithPrev]
else
LTmpOptions := [];
TmpS := Model.Lines.LineBreak;
Model.InsertAfter(CaretPosition, TmpS, LTmpOptions + [TInsertOption.MoveCaret, TInsertOption.CanUndo]);
Model.SelLength := 0;
Key := 0;
DoChange;
end;
IsCtrlOrCmd := Shift * [ssCtrl, ssCommand] <> [];
case Key of
vkA:
if IsCtrlOrCmd then
begin
Memo.SelectAll;
KeyHandled := True;
end;
vkC:
if IsCtrlOrCmd then
begin
Memo.CopyToClipboard;
KeyHandled := True;
end;
vkV:
if IsCtrlOrCmd then
begin
Memo.PasteFromClipboard;
KeyHandled := True;
end;
vkX:
if IsCtrlOrCmd and not Model.ReadOnly then
begin
Memo.CutToClipboard;
KeyHandled := True;
end;
vkZ:
if IsCtrlOrCmd then
begin
DoUndo(nil);
KeyHandled := True;
end;
vkEnd:
begin
if IsCtrlOrCmd then
GotoTextEnd
else
GotoLineEnd;
KeyHandled := True;
end;
vkHome:
begin
if IsCtrlOrCmd then
GotoTextBegin
else
GotoLineBegin;
KeyHandled := True;
end;
vkLeft:
begin
if IsCtrlOrCmd then
CaretPosition := GetPrevWordBegin(CaretPosition)
else
MoveCaretLeft;
KeyHandled := True;
end;
vkRight:
begin
if IsCtrlOrCmd then
CaretPosition := GetNextWordBegin(CaretPosition)
else
MoveCaretRight;
KeyHandled := True;
end;
vkUp:
begin
if IsCtrlOrCmd then
DoScroll(-1)
else
MoveCaretUp;
KeyHandled := True;
end;
vkDown:
begin
if IsCtrlOrCmd then
DoScroll(1)
else
MoveCaretDown;
KeyHandled := True;
end;
vkPrior:
begin
MoveCaretPageUp;
KeyHandled := True;
end;
vkNext:
begin
MoveCaretPageDown;
KeyHandled := True;
end;
vkDelete:
begin
if not Model.ReadOnly then
if Model.SelLength <> 0 then
begin
if ssShift in Shift then
Memo.CutToClipboard
else
Memo.DeleteSelection;
end
else if IsCtrlOrCmd then
Model.DeleteFrom(CaretPosition, Min(FMX.Text.GetLexemeEnd(Model.Lines[CaretPosition.Line],
CaretPosition.Pos), Model.Lines[CaretPosition.Line].Length) - CaretPosition.Pos + 1,
[TDeleteOption.CanUndo])
else if Model.Lines.Count > 0 then
begin
if (CaretPosition.Pos < Model.Lines[CaretPosition.Line].Length) and
Model.Lines[CaretPosition.Line].Chars[CaretPosition.Pos].IsHighSurrogate then
Model.DeleteFrom(CaretPosition, 2, [TDeleteOption.CanUndo])
else
Model.DeleteFrom(CaretPosition, 1, [TDeleteOption.CanUndo]);
end;
KeyHandled := True;
end;
vkBack:
begin
if not Model.ReadOnly then
if Model.SelLength <> 0 then
Memo.DeleteSelection
else if IsCtrlOrCmd then
begin
// Deleting whole word
LCaret := GetPrevWordBegin(CaretPosition);
if LCaret.IsInvalid then
Exit;
Model.DeleteFrom(LCaret, Model.PosToTextPos(CaretPosition) - Model.PosToTextPos(LCaret),
[TDeleteOption.MoveCaret, TDeleteOption.CanUndo]);
end
else
// Deleting single character
if Model.PosToTextPos(CaretPosition) > 0 then
begin
if (Model.Lines[CaretPosition.Line].Length > 0) and
Model.Lines[CaretPosition.Line].Chars[CaretPosition.Pos - 1].IsLowSurrogate then
Model.DeleteFrom(GetPositionShift(CaretPosition, -2), 2,
[TDeleteOption.MoveCaret, TDeleteOption.CanUndo])
else
Model.DeleteFrom(GetPositionShift(CaretPosition, -1), 1,
[TDeleteOption.MoveCaret, TDeleteOption.CanUndo]);
end;
KeyHandled := True;
end;
vkInsert:
begin
if IsCtrlOrCmd then
begin
Memo.CopyToClipboard;
KeyHandled := True;
end
else if [ssShift] * Shift <> [] then
begin
Memo.PasteFromClipboard;
KeyHandled := True;
end;
end;
end;
if (KeyChar <> #0) and not Model.ReadOnly then
begin
FCharsBuffer := FCharsBuffer + KeyChar;
if not KeyChar.IsHighSurrogate then
begin
WasSelection := Model.SelLength > 0;
if WasSelection then
Model.DeleteFrom(GetSelBeg, Model.SelLength, [TDeleteOption.MoveCaret, TDeleteOption.CanUndo]);
if WasSelection then
LTmpOptions := [TInsertOption.UndoPairedWithPrev]
else
LTmpOptions := [];
Model.InsertAfter(CaretPosition, FCharsBuffer, LTmpOptions + [TInsertOption.MoveCaret, TInsertOption.CanUndo,
TInsertOption.Typed]);
FCharsBuffer := string.Empty;
Model.SelLength := 0;
end;
KeyHandled := True;
end
else
begin
FCharsBuffer := string.Empty;
if (Key in [vkEnd, vkHome, vkLeft, vkRight, vkUp, vkDown, vkPrior, vkNext]) then
begin
if ssShift in Shift then
begin
if not FSelected then
SelectAtPos(OldCaretPosition);
SelectAtPos(CaretPosition);
end
else if FSelected then
begin
FSelected := False;
UpdateSelectionInModel;
end;
RepaintEdit;
KeyHandled := True;
end;
end;
UpdateSelectionPointPositions;
if KeyHandled then
begin
Key := 0;
KeyChar := #0;
end;
end;