-
Notifications
You must be signed in to change notification settings - Fork 137
/
TextView.cs
2101 lines (1839 loc) · 81.7 KB
/
TextView.cs
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
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, new DocumentChangedEventArgs(oldValue, newValue));
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Insert(index, item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}