aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Editing/SelectionMouseHandler.cs
blob: 3c5ec51dc0387ae69fcfacd012b3c999291c6ae3 (plain)
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
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.TextFormatting;
using System.Windows.Threading;
using Tango.Scripting.Editors.Document;
using Tango.Scripting.Editors.Rendering;
using Tango.Scripting.Editors.Utils;

namespace Tango.Scripting.Editors.Editing
{
	/// <summary>
	/// Handles selection of text using the mouse.
	/// </summary>
	sealed class SelectionMouseHandler : ITextAreaInputHandler
	{
		#region enum SelectionMode
		enum SelectionMode
		{
			/// <summary>
			/// no selection (no mouse button down)
			/// </summary>
			None,
			/// <summary>
			/// left mouse button down on selection, might be normal click
			/// or might be drag'n'drop
			/// </summary>
			PossibleDragStart,
			/// <summary>
			/// dragging text
			/// </summary>
			Drag,
			/// <summary>
			/// normal selection (click+drag)
			/// </summary>
			Normal,
			/// <summary>
			/// whole-word selection (double click+drag or ctrl+click+drag)
			/// </summary>
			WholeWord,
			/// <summary>
			/// whole-line selection (triple click+drag)
			/// </summary>
			WholeLine,
			/// <summary>
			/// rectangular selection (alt+click+drag)
			/// </summary>
			Rectangular
		}
		#endregion
		
		readonly TextArea textArea;
		
		SelectionMode mode;
		AnchorSegment startWord;
		Point possibleDragStartMousePos;
		
		#region Constructor + Attach + Detach
		public SelectionMouseHandler(TextArea textArea)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			this.textArea = textArea;
		}
		
		public TextArea TextArea {
			get { return textArea; }
		}
		
		public void Attach()
		{
			textArea.MouseLeftButtonDown += textArea_MouseLeftButtonDown;
			textArea.MouseMove += textArea_MouseMove;
			textArea.MouseLeftButtonUp += textArea_MouseLeftButtonUp;
			textArea.QueryCursor += textArea_QueryCursor;
			textArea.OptionChanged += textArea_OptionChanged;
			
			enableTextDragDrop = textArea.Options.EnableTextDragDrop;
			if (enableTextDragDrop) {
				AttachDragDrop();
			}
		}
		
		public void Detach()
		{
			mode = SelectionMode.None;
			textArea.MouseLeftButtonDown -= textArea_MouseLeftButtonDown;
			textArea.MouseMove -= textArea_MouseMove;
			textArea.MouseLeftButtonUp -= textArea_MouseLeftButtonUp;
			textArea.QueryCursor -= textArea_QueryCursor;
			textArea.OptionChanged -= textArea_OptionChanged;
			if (enableTextDragDrop) {
				DetachDragDrop();
			}
		}
		
		void AttachDragDrop()
		{
			textArea.AllowDrop = true;
			textArea.GiveFeedback += textArea_GiveFeedback;
			textArea.QueryContinueDrag += textArea_QueryContinueDrag;
			textArea.DragEnter += textArea_DragEnter;
			textArea.DragOver += textArea_DragOver;
			textArea.DragLeave += textArea_DragLeave;
			textArea.Drop += textArea_Drop;
		}
		
		void DetachDragDrop()
		{
			textArea.AllowDrop = false;
			textArea.GiveFeedback -= textArea_GiveFeedback;
			textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
			textArea.DragEnter -= textArea_DragEnter;
			textArea.DragOver -= textArea_DragOver;
			textArea.DragLeave -= textArea_DragLeave;
			textArea.Drop -= textArea_Drop;
		}
		
		bool enableTextDragDrop;
		
		void textArea_OptionChanged(object sender, PropertyChangedEventArgs e)
		{
			bool newEnableTextDragDrop = textArea.Options.EnableTextDragDrop;
			if (newEnableTextDragDrop != enableTextDragDrop) {
				enableTextDragDrop = newEnableTextDragDrop;
				if (newEnableTextDragDrop)
					AttachDragDrop();
				else
					DetachDragDrop();
			}
		}
		#endregion
		
		#region Dropping text
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_DragEnter(object sender, DragEventArgs e)
		{
			try {
				e.Effects = GetEffect(e);
				textArea.Caret.Show();
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_DragOver(object sender, DragEventArgs e)
		{
			try {
				e.Effects = GetEffect(e);
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}
		
		DragDropEffects GetEffect(DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
				e.Handled = true;
				int visualColumn;
				int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn);
				if (offset >= 0) {
					textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn);
					textArea.Caret.DesiredXPos = double.NaN;
					if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
						if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
						    && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
						{
							return DragDropEffects.Move;
						} else {
							return e.AllowedEffects & DragDropEffects.Copy;
						}
					}
				}
			}
			return DragDropEffects.None;
		}
		
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_DragLeave(object sender, DragEventArgs e)
		{
			try {
				e.Handled = true;
				if (!textArea.IsKeyboardFocusWithin)
					textArea.Caret.Hide();
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}
		
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_Drop(object sender, DragEventArgs e)
		{
			try {
				DragDropEffects effect = GetEffect(e);
				e.Effects = effect;
				if (effect != DragDropEffects.None) {
					string text = e.Data.GetData(DataFormats.UnicodeText, true) as string;
					if (text != null) {
						int start = textArea.Caret.Offset;
						if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
							Debug.WriteLine("Drop: did not drop: drop target is inside selection");
							e.Effects = DragDropEffects.None;
						} else {
							Debug.WriteLine("Drop: insert at " + start);
							
							bool rectangular = e.Data.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
							
							string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
							text = TextUtilities.NormalizeNewLines(text, newLine);
							
							// Mark the undo group with the currentDragDescriptor, if the drag
							// is originating from the same control. This allows combining
							// the undo groups when text is moved.
							textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
							try {
								if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
									
								} else {
									textArea.Document.Insert(start, text);
									textArea.Selection = Selection.Create(textArea, start, start + text.Length);
								}
							} finally {
								textArea.Document.UndoStack.EndUndoGroup();
							}
						}
						e.Handled = true;
					}
				}
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}
		
		void OnDragException(Exception ex)
		{
			// WPF swallows exceptions during drag'n'drop or reports them incorrectly, so
			// we re-throw them later to allow the application's unhandled exception handler
			// to catch them
			textArea.Dispatcher.BeginInvoke(
				DispatcherPriority.Normal,
				new Action(delegate {
				           	throw new DragDropException("Exception during drag'n'drop", ex);
				           }));
		}
		
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
		{
			try {
				e.UseDefaultCursors = true;
				e.Handled = true;
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}
		
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
		{
			try {
				if (e.EscapePressed) {
					e.Action = DragAction.Cancel;
				} else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
					e.Action = DragAction.Drop;
				} else {
					e.Action = DragAction.Continue;
				}
				e.Handled = true;
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}
		#endregion
		
		#region Start Drag
		object currentDragDescriptor;
		
		void StartDrag()
		{
			// prevent nested StartDrag calls
			mode = SelectionMode.Drag;
			
			// mouse capture and Drag'n'Drop doesn't mix
			textArea.ReleaseMouseCapture();
			
			DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
			
			DragDropEffects allowedEffects = DragDropEffects.All;
			var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
			foreach (ISegment s in deleteOnMove) {
				ISegment[] result = textArea.GetDeletableSegments(s);
				if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
					allowedEffects &= ~DragDropEffects.Move;
				}
			}
			
			object dragDescriptor = new object();
			this.currentDragDescriptor = dragDescriptor;
			
			DragDropEffects resultEffect;
			using (textArea.AllowCaretOutsideSelection()) {
				var oldCaretPosition = textArea.Caret.Position;
				try {
					Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
					resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
					Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
				} catch (COMException ex) {
					// ignore COM errors - don't crash on badly implemented drop targets
					Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
					return;
				}
				if (resultEffect == DragDropEffects.None) {
					// reset caret if drag was aborted
					textArea.Caret.Position = oldCaretPosition;
				}
			}
			
			this.currentDragDescriptor = null;
			
			if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
				bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
				if (draggedInsideSingleDocument)
					textArea.Document.UndoStack.StartContinuedUndoGroup(null);
				textArea.Document.BeginUpdate();
				try {
					foreach (ISegment s in deleteOnMove) {
						textArea.Document.Remove(s.Offset, s.Length);
					}
				} finally {
					textArea.Document.EndUpdate();
					if (draggedInsideSingleDocument)
						textArea.Document.UndoStack.EndUndoGroup();
				}
			}
		}
		#endregion
		
		#region QueryCursor
		// provide the IBeam Cursor for the text area
		void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
		{
			if (!e.Handled) {
				if (mode != SelectionMode.None || !enableTextDragDrop) {
					e.Cursor = Cursors.IBeam;
					e.Handled = true;
				} else if (textArea.TextView.VisualLinesValid) {
					// Only query the cursor if the visual lines are valid.
					// If they are invalid, the cursor will get re-queried when the visual lines
					// get refreshed.
					Point p = e.GetPosition(textArea.TextView);
					if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
						int visualColumn;
						int offset = GetOffsetFromMousePosition(e, out visualColumn);
						if (textArea.Selection.Contains(offset))
							e.Cursor = Cursors.Arrow;
						else
							e.Cursor = Cursors.IBeam;
						e.Handled = true;
					}
				}
			}
		}
		#endregion
		
		#region LeftButtonDown
		void textArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			mode = SelectionMode.None;
			if (!e.Handled && e.ChangedButton == MouseButton.Left) {
				ModifierKeys modifiers = Keyboard.Modifiers;
				bool shift = (modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;
				if (enableTextDragDrop && e.ClickCount == 1 && !shift) {
					int visualColumn;
					int offset = GetOffsetFromMousePosition(e, out visualColumn);
					if (textArea.Selection.Contains(offset)) {
						if (textArea.CaptureMouse()) {
							mode = SelectionMode.PossibleDragStart;
							possibleDragStartMousePos = e.GetPosition(textArea);
						}
						e.Handled = true;
						return;
					}
				}
				
				var oldPosition = textArea.Caret.Position;
				SetCaretOffsetToMousePosition(e);
				
				
				if (!shift) {
					textArea.ClearSelection();
				}
				if (textArea.CaptureMouse()) {
					if ((modifiers & ModifierKeys.Alt) == ModifierKeys.Alt && textArea.Options.EnableRectangularSelection) {
						mode = SelectionMode.Rectangular;
						if (shift && textArea.Selection is RectangleSelection) {
							textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
						}
					} else if (e.ClickCount == 1 && ((modifiers & ModifierKeys.Control) == 0)) {
						mode = SelectionMode.Normal;
						if (shift && !(textArea.Selection is RectangleSelection)) {
							textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
						}
					} else {
						SimpleSegment startWord;
						if (e.ClickCount == 3) {
							mode = SelectionMode.WholeLine;
							startWord = GetLineAtMousePosition(e);
						} else {
							mode = SelectionMode.WholeWord;
							startWord = GetWordAtMousePosition(e);
						}
						if (startWord == SimpleSegment.Invalid) {
							mode = SelectionMode.None;
							textArea.ReleaseMouseCapture();
							return;
						}
						if (shift && !textArea.Selection.IsEmpty) {
							if (startWord.Offset < textArea.Selection.SurroundingSegment.Offset) {
								textArea.Selection = textArea.Selection.SetEndpoint(new TextViewPosition(textArea.Document.GetLocation(startWord.Offset)));
							} else if (startWord.EndOffset > textArea.Selection.SurroundingSegment.EndOffset) {
								textArea.Selection = textArea.Selection.SetEndpoint(new TextViewPosition(textArea.Document.GetLocation(startWord.EndOffset)));
							}
							this.startWord = new AnchorSegment(textArea.Document, textArea.Selection.SurroundingSegment);
						} else {
							textArea.Selection = Selection.Create(textArea, startWord.Offset, startWord.EndOffset);
							this.startWord = new AnchorSegment(textArea.Document, startWord.Offset, startWord.Length);
						}
					}
				}
			}
			e.Handled = true;
		}
		#endregion
		
		#region Mouse Position <-> Text coordinates
		SimpleSegment GetWordAtMousePosition(MouseEventArgs e)
		{
			TextView textView = textArea.TextView;
			if (textView == null) return SimpleSegment.Invalid;
			Point pos = e.GetPosition(textView);
			if (pos.Y < 0)
				pos.Y = 0;
			if (pos.Y > textView.ActualHeight)
				pos.Y = textView.ActualHeight;
			pos += textView.ScrollOffset;
			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
			if (line != null) {
				int visualColumn = line.GetVisualColumn(pos, textArea.Selection.EnableVirtualSpace);
				int wordStartVC = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, textArea.Selection.EnableVirtualSpace);
				if (wordStartVC == -1)
					wordStartVC = 0;
				int wordEndVC = line.GetNextCaretPosition(wordStartVC, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, textArea.Selection.EnableVirtualSpace);
				if (wordEndVC == -1)
					wordEndVC = line.VisualLength;
				int relOffset = line.FirstDocumentLine.Offset;
				int wordStartOffset = line.GetRelativeOffset(wordStartVC) + relOffset;
				int wordEndOffset = line.GetRelativeOffset(wordEndVC) + relOffset;
				return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
			} else {
				return SimpleSegment.Invalid;
			}
		}
		
		SimpleSegment GetLineAtMousePosition(MouseEventArgs e)
		{
			TextView textView = textArea.TextView;
			if (textView == null) return SimpleSegment.Invalid;
			Point pos = e.GetPosition(textView);
			if (pos.Y < 0)
				pos.Y = 0;
			if (pos.Y > textView.ActualHeight)
				pos.Y = textView.ActualHeight;
			pos += textView.ScrollOffset;
			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
			if (line != null) {
				return new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset);
			} else {
				return SimpleSegment.Invalid;
			}
		}
		
		int GetOffsetFromMousePosition(MouseEventArgs e, out int visualColumn)
		{
			return GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn);
		}
		
		int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn)
		{
			visualColumn = 0;
			TextView textView = textArea.TextView;
			Point pos = positionRelativeToTextView;
			if (pos.Y < 0)
				pos.Y = 0;
			if (pos.Y > textView.ActualHeight)
				pos.Y = textView.ActualHeight;
			pos += textView.ScrollOffset;
			if (pos.Y > textView.DocumentHeight)
				pos.Y = textView.DocumentHeight - ExtensionMethods.Epsilon;
			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
			if (line != null) {
				visualColumn = line.GetVisualColumn(pos, textArea.Selection.EnableVirtualSpace);
				return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
			}
			return -1;
		}
		
		int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
		{
			visualColumn = 0;
			TextView textView = textArea.TextView;
			Point pos = positionRelativeToTextView;
			if (pos.Y < 0)
				pos.Y = 0;
			if (pos.Y > textView.ActualHeight)
				pos.Y = textView.ActualHeight;
			pos += textView.ScrollOffset;
			if (pos.Y > textView.DocumentHeight)
				pos.Y = textView.DocumentHeight - ExtensionMethods.Epsilon;
			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
			if (line != null) {
				visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, textArea.Selection.EnableVirtualSpace);
				return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
			}
			return -1;
		}
		#endregion
		
		#region MouseMove
		void textArea_MouseMove(object sender, MouseEventArgs e)
		{
			if (e.Handled)
				return;
			if (mode == SelectionMode.Normal || mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine || mode == SelectionMode.Rectangular) {
				e.Handled = true;
				if (textArea.TextView.VisualLinesValid) {
					// If the visual lines are not valid, don't extend the selection.
					// Extending the selection forces a VisualLine refresh, and it is sufficient
					// to do that on MouseUp, we don't have to do it every MouseMove.
					ExtendSelectionToMouse(e);
				}
			} else if (mode == SelectionMode.PossibleDragStart) {
				e.Handled = true;
				Vector mouseMovement = e.GetPosition(textArea) - possibleDragStartMousePos;
				if (Math.Abs(mouseMovement.X) > SystemParameters.MinimumHorizontalDragDistance
				    || Math.Abs(mouseMovement.Y) > SystemParameters.MinimumVerticalDragDistance)
				{
					StartDrag();
				}
			}
		}
		#endregion
		
		#region ExtendSelection
		void SetCaretOffsetToMousePosition(MouseEventArgs e)
		{
			SetCaretOffsetToMousePosition(e, null);
		}
		
		void SetCaretOffsetToMousePosition(MouseEventArgs e, ISegment allowedSegment)
		{
			int visualColumn;
			int offset;
			if (mode == SelectionMode.Rectangular)
				offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(textArea.TextView), out visualColumn);
			else
				offset = GetOffsetFromMousePosition(e, out visualColumn);
			if (allowedSegment != null) {
				offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
			}
			if (offset >= 0) {
				textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn);
				textArea.Caret.DesiredXPos = double.NaN;
			}
		}
		
		void ExtendSelectionToMouse(MouseEventArgs e)
		{
			TextViewPosition oldPosition = textArea.Caret.Position;
			if (mode == SelectionMode.Normal || mode == SelectionMode.Rectangular) {
				SetCaretOffsetToMousePosition(e);
				if (mode == SelectionMode.Normal && textArea.Selection is RectangleSelection)
					textArea.Selection = new SimpleSelection(textArea, oldPosition, textArea.Caret.Position);
				else if (mode == SelectionMode.Rectangular && !(textArea.Selection is RectangleSelection))
					textArea.Selection = new RectangleSelection(textArea, oldPosition, textArea.Caret.Position);
				else
					textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
			} else if (mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine) {
				var newWord = (mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
				if (newWord != SimpleSegment.Invalid) {
					textArea.Selection = Selection.Create(textArea,
					                                      Math.Min(newWord.Offset, startWord.Offset),
					                                      Math.Max(newWord.EndOffset, startWord.EndOffset));
					// Set caret offset, but limit the caret to stay inside the selection.
					// in whole-word selection, it's otherwise possible that we get the caret outside the
					// selection - but the TextArea doesn't like that and will reset the selection, causing
					// flickering.
					SetCaretOffsetToMousePosition(e, textArea.Selection.SurroundingSegment);
				}
			}
			textArea.Caret.BringCaretToView(5.0);
		}
		#endregion
		
		#region MouseLeftButtonUp
		void textArea_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			if (mode == SelectionMode.None || e.Handled)
				return;
			e.Handled = true;
			if (mode == SelectionMode.PossibleDragStart) {
				// -> this was not a drag start (mouse didn't move after mousedown)
				SetCaretOffsetToMousePosition(e);
				textArea.ClearSelection();
			} else if (mode == SelectionMode.Normal || mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine || mode == SelectionMode.Rectangular) {
				ExtendSelectionToMouse(e);
			}
			mode = SelectionMode.None;
			textArea.ReleaseMouseCapture();
		}
		#endregion
	}
}
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. void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { if (!keepElement && ior.Element.IsKeyboardFocusWithin) { // When the inline element that has the focus is removed, WPF 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) RemoveVisualChild(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly DependencyProperty NonPrintableCharacterBrushProperty = DependencyProperty.Register("NonPrintableCharacterBrush", typeof(Brush), typeof(TextView), new FrameworkPropertyMetadata(Brushes.LightGray)); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public Brush NonPrintableCharacterBrush { get { return (Brush)GetValue(NonPrintableCharacterBrushProperty); } set { SetValue(NonPrintableCharacterBrushProperty, value); } } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly DependencyProperty LinkTextForegroundBrushProperty = DependencyProperty.Register("LinkTextForegroundBrush", typeof(Brush), typeof(TextView), new FrameworkPropertyMetadata(Brushes.Gray)); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public Brush LinkTextForegroundBrush { get { return (Brush)GetValue(LinkTextForegroundBrushProperty); } set { SetValue(LinkTextForegroundBrushProperty, value); } } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly DependencyProperty LinkTextBackgroundBrushProperty = DependencyProperty.Register("LinkTextBackgroundBrush", typeof(Brush), typeof(TextView), new FrameworkPropertyMetadata(Brushes.Transparent)); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public Brush LinkTextBackgroundBrush { get { return (Brush)GetValue(LinkTextBackgroundBrushProperty); } set { SetValue(LinkTextBackgroundBrushProperty, value); } } #endregion #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { Redraw(DispatcherPriority.Normal); } /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw(DispatcherPriority redrawPriority) { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(redrawPriority); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority = DispatcherPriority.Normal) { VerifyAccess(); if (allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(redrawPriority); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length, DispatcherPriority redrawPriority = DispatcherPriority.Normal) { VerifyAccess(); bool changedSomethingBeforeOrInLine = false; for (int i = 0; i < allVisualLines.Count; i++) { VisualLine visualLine = allVisualLines[i]; int lineStart = visualLine.FirstDocumentLine.Offset; int 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(redrawPriority); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [System.Diagnostics.CodeAnalysis.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(DispatcherPriority.Normal); } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [System.Diagnostics.CodeAnalysis.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, DispatcherPriority priority) { InvalidateMeasure(priority); } /// <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, DispatcherPriority redrawPriority = DispatcherPriority.Normal) { if (segment != null) { Redraw(segment.Offset, segment.Length, redrawPriority); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> void ClearVisualLines() { visibleVisualLines = null; if (allVisualLines.Count != 0) { foreach (VisualLine visualLine in allVisualLines) { DisposeVisualLine(visualLine); } allVisualLines.Clear(); } } void DisposeVisualLine(VisualLine visualLine) { if (newVisualLines != null && newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visibleVisualLines = null; visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region InvalidateMeasure(DispatcherPriority) DispatcherOperation invalidateMeasureOperation; void InvalidateMeasure(DispatcherPriority priority) { if (priority >= DispatcherPriority.Render) { if (invalidateMeasureOperation != null) { invalidateMeasureOperation.Abort(); invalidateMeasureOperation = null; } base.InvalidateMeasure(); } else { if (invalidateMeasureOperation != null) { invalidateMeasureOperation.Priority = priority; } else { invalidateMeasureOperation = Dispatcher.BeginInvoke( priority, new Action( delegate { invalidateMeasureOperation = null; base.InvalidateMeasure(); } ) ); } } } #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 (VisualLine visualLine in allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); int start = visualLine.FirstDocumentLine.LineNumber; int 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) List<VisualLine> allVisualLines = new List<VisualLine>(); ReadOnlyCollection<VisualLine> visibleVisualLines; double clippedPixelsOnTop; 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> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (visibleVisualLines == null) { return new ReadOnlyCollection<VisualLine>(new List<VisualLine>()); } else { 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 { get { return 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.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(DispatcherPriority.Normal); // force immediate re-measure UpdateLayout(); } // 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); // UpdateLayout(); } //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> const double AdditionalHorizontalScrollAmount = 3; Size lastAvailableSize; 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.Width = 32000; if (!canHorizontallyScroll && !availableSize.Width.IsClose(lastAvailableSize.Width)) ClearVisualLines(); lastAvailableSize = availableSize; foreach (UIElement layer in layers) { layer.Measure(availableSize); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (document == null) { // no document -> create empty list of lines allVisualLines = new List<VisualLine>(); visibleVisualLines = allVisualLines.AsReadOnly(); 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; double heightTreeHeight = this.DocumentHeight; TextEditorOptions options = this.Options; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(scrollViewport.Height)) { heightTreeHeight = Math.Max(heightTreeHeight, Math.Min(heightTreeHeight - 50, scrollOffset.Y) + scrollViewport.Height); } } textLayer.SetVisualLines(visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight), scrollOffset); if (VisualLinesChanged != null) VisualLinesChanged(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> 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>(); if (VisualLineConstructionStarting != null) VisualLineConstructionStarting(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = elementGenerators.ToArray(); var lineTransformersArray = lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; double yPos = -clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { VisualLine visualLine = GetVisualLine(nextLine.LineNumber); if (visualLine == null) { visualLine = BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); } visualLine.VisualTop = scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (TextLine textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } newVisualLines.Add(visualLine); } foreach (VisualLine line in allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!newVisualLines.Contains(line)) DisposeVisualLine(line); } allVisualLines = newVisualLines; // visibleVisualLines = readonly copy of visual lines visibleVisualLines = new ReadOnlyCollection<VisualLine>(newVisualLines.ToArray()); newVisualLines = null; if (allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine TextFormatter formatter; internal TextViewCachedElements cachedElements; TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = (Brush)GetValue(Control.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, VisualLineElementGenerator[] elementGeneratorsArray, IVisualLineTransformer[] lineTransformersArray, Size availableSize) { if (heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: int textOffset = 0; TextLineBreak lastLineBreak = null; var textLines = new List<TextLine>(); paragraphProperties.indent = 0; paragraphProperties.firstLineInParagraph = true; while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { TextLine textLine = formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.GetTextLineBreak(); } visualLine.SetTextLines(textLines); heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; int column = 0; int elementIndex = 0; VisualLineElement element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (UIElement layer in layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (document == null || allVisualLines.Count == 0) return finalSize; // validate scroll position Vector newScrollOffset = scrollOffset; if (scrollOffset.X + finalSize.Width > scrollExtent.Width) { newScrollOffset.X = Math.Max(0, scrollExtent.Width - finalSize.Width); } if (scrollOffset.Y + finalSize.Height > scrollExtent.Height) { newScrollOffset.Y = Math.Max(0, scrollExtent.Height - finalSize.Height); } if (SetScrollData(scrollViewport, scrollExtent, newScrollOffset)) InvalidateMeasure(DispatcherPriority.Normal); //Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + scrollOffset); // double maxWidth = 0; if (visibleVisualLines != null) { Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop); foreach (VisualLine visualLine in visibleVisualLines) { int offset = 0; foreach (TextLine textLine in visualLine.TextLines) { foreach (var span in textLine.GetTextRunSpans()) { InlineObjectRun inline = span.Value as InlineObjectRun; if (inline != null && inline.VisualLine != null) { Debug.Assert(inlineObjects.Contains(inline)); double distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset, 0)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); } offset += span.Length; } pos.Y += textLine.Height; } } } InvalidateCursor(); return finalSize; } #endregion #region Render readonly ObserveAddRemoveCollection<IBackgroundRenderer> backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers { get { return backgroundRenderers; } } void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> protected override void OnRender(DrawingContext drawingContext) { RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in visibleVisualLines) { Brush currentBrush = null; int startVC = 0; int length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder(); builder.AlignToWholePixels = true; builder.CornerRadius = 3; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVC, startVC + length)) builder.AddRectangle(this, rect); Geometry geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVC = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder(); builder.AlignToWholePixels = true; builder.CornerRadius = 3; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVC, startVC + length)) builder.AddRectangle(this, rect); Geometry geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (IBackgroundRenderer bg in backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop); foreach (VisualLineDrawingVisual visual in visuals) { TranslateTransform t = visual.Transform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.Transform = new TranslateTransform(pos.X, pos.Y); visual.Transform.Freeze(); } pos.Y += visual.Height; } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the document, in pixels. /// </summary> Size scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> Vector scrollOffset; /// <summary> /// Size of the viewport. /// </summary> Size scrollViewport; void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(this.scrollViewport) && extent.IsClose(this.scrollExtent) && offset.IsClose(this.scrollOffset))) { this.scrollViewport = viewport; this.scrollExtent = extent; SetScrollOffset(offset); this.OnScrollChange(); return true; } return false; } void OnScrollChange() { ScrollViewer scrollOwner = ((IScrollInfo)this).ScrollOwner; if (scrollOwner != null) { scrollOwner.InvalidateScrollInfo(); } } bool canVerticallyScroll; bool IScrollInfo.CanVerticallyScroll { get { return canVerticallyScroll; } set { if (canVerticallyScroll != value) { canVerticallyScroll = value; InvalidateMeasure(DispatcherPriority.Normal); } } } bool canHorizontallyScroll; bool IScrollInfo.CanHorizontallyScroll { get { return canHorizontallyScroll; } set { if (canHorizontallyScroll != value) { canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(DispatcherPriority.Normal); } } } double IScrollInfo.ExtentWidth { get { return scrollExtent.Width; } } double IScrollInfo.ExtentHeight { get { return scrollExtent.Height; } } double IScrollInfo.ViewportWidth { get { return scrollViewport.Width; } } double IScrollInfo.ViewportHeight { get { return scrollViewport.Height; } } /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset { get { return scrollOffset.X; } } /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset { get { return scrollOffset.Y; } } /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset { get { return scrollOffset; } } /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; void SetScrollOffset(Vector vector) { if (!canHorizontallyScroll) vector.X = 0; if (!canVerticallyScroll) vector.Y = 0; if (!scrollOffset.IsClose(vector)) { scrollOffset = vector; if (ScrollOffsetChanged != null) ScrollOffsetChanged(this, EventArgs.Empty); } } ScrollViewer IScrollInfo.ScrollOwner { get; set; } void IScrollInfo.LineUp() { ((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - DefaultLineHeight); } void IScrollInfo.LineDown() { ((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + DefaultLineHeight); } void IScrollInfo.LineLeft() { ((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - WideSpaceWidth); } void IScrollInfo.LineRight() { ((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + WideSpaceWidth); } void IScrollInfo.PageUp() { ((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - scrollViewport.Height); } void IScrollInfo.PageDown() { ((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + scrollViewport.Height); } void IScrollInfo.PageLeft() { ((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - scrollViewport.Width); } void IScrollInfo.PageRight() { ((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + scrollViewport.Width); } void IScrollInfo.MouseWheelUp() { ((IScrollInfo)this).SetVerticalOffset( scrollOffset.Y - (SystemParameters.WheelScrollLines * DefaultLineHeight)); OnScrollChange(); } void IScrollInfo.MouseWheelDown() { ((IScrollInfo)this).SetVerticalOffset( scrollOffset.Y + (SystemParameters.WheelScrollLines * DefaultLineHeight)); OnScrollChange(); } void IScrollInfo.MouseWheelLeft() { ((IScrollInfo)this).SetHorizontalOffset( scrollOffset.X - (SystemParameters.WheelScrollLines * WideSpaceWidth)); OnScrollChange(); } void IScrollInfo.MouseWheelRight() { ((IScrollInfo)this).SetHorizontalOffset( scrollOffset.X + (SystemParameters.WheelScrollLines * WideSpaceWidth)); OnScrollChange(); } bool defaultTextMetricsValid; double wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. double defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. double defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return defaultBaseline; } } void InvalidateDefaultTextMetrics() { defaultTextMetricsValid = false; if (heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } void CalculateDefaultTextMetrics() { if (defaultTextMetricsValid) return; defaultTextMetricsValid = true; if (formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); using (var line = formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null)) { wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); defaultBaseline = Math.Max(1, line.Baseline); defaultLineHeight = Math.Max(1, line.Height); } } else { wideSpaceWidth = FontSize / 2; defaultBaseline = FontSize; defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (heightTree != null) heightTree.DefaultLineHeight = defaultLineHeight; } static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; else return offset; } void IScrollInfo.SetHorizontalOffset(double offset) { offset = ValidateVisualOffset(offset); if (!scrollOffset.X.IsClose(offset)) { SetScrollOffset(new Vector(offset, scrollOffset.Y)); InvalidateVisual(); textLayer.InvalidateVisual(); } } void IScrollInfo.SetVerticalOffset(double offset) { offset = ValidateVisualOffset(offset); if (!scrollOffset.Y.IsClose(offset)) { SetScrollOffset(new Vector(scrollOffset.X, offset)); InvalidateMeasure(DispatcherPriority.Normal); } } Rect IScrollInfo.MakeVisible(Visual visual, Rect rectangle) { if (rectangle.IsEmpty || visual == null || visual == this || !this.IsAncestorOf(visual)) { return Rect.Empty; } // Convert rectangle into our coordinate space. GeneralTransform childTransform = visual.TransformToAncestor(this); rectangle = childTransform.TransformBounds(rectangle); MakeVisible(Rect.Offset(rectangle, scrollOffset)); return rectangle; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public void MakeVisible(Rect rectangle) { Rect visibleRectangle = new Rect(scrollOffset.X, scrollOffset.Y, scrollViewport.Width, scrollViewport.Height); Vector newScrollOffset = scrollOffset; if (rectangle.Left < visibleRectangle.Left) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffset.X = rectangle.Left + rectangle.Width / 2; } else { newScrollOffset.X = rectangle.Left; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffset.X = rectangle.Right - scrollViewport.Width; } if (rectangle.Top < visibleRectangle.Top) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffset.Y = rectangle.Top + rectangle.Height / 2; } else { newScrollOffset.Y = rectangle.Top; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffset.Y = rectangle.Bottom - scrollViewport.Height; } newScrollOffset.X = ValidateVisualOffset(newScrollOffset.X); newScrollOffset.Y = ValidateVisualOffset(newScrollOffset.Y); if (!scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); this.OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } #endregion #region Visual element mouse handling /// <inheritdoc/> protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) { // accept clicks even where the text area draws no background return new PointHitTestResult(this, hitTestParameters.HitPoint); } [ThreadStatic] static bool invalidCursor; /// <summary> /// Updates the mouse cursor by calling <see cref="Mouse.UpdateCursor"/>, but with input priority. /// </summary> public static void InvalidateCursor() { if (!invalidCursor) { invalidCursor = true; Dispatcher.CurrentDispatcher.BeginInvoke( DispatcherPriority.Input, new Action( delegate { invalidCursor = false; Mouse.UpdateCursor(); })); } } /// <inheritdoc/> protected override void OnQueryCursor(QueryCursorEventArgs e) { VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset); if (element != null) { element.OnQueryCursor(e); } } /// <inheritdoc/> protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { EnsureVisualLines(); VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset); if (element != null) { element.OnMouseDown(e); } } } /// <inheritdoc/> protected override void OnMouseUp(MouseButtonEventArgs e) { base.OnMouseUp(e); if (!e.Handled) { EnsureVisualLines(); VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset); if (element != null) { element.OnMouseUp(e); } } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (VisualLine vl in this.VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return heightTree.GetVisualPosition(heightTree.GetLineByNumber(line)); } VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { VisualLine vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { int column = vl.GetVisualColumnFloor(visualPosition); // Debug.WriteLine(vl.FirstDocumentLine.LineNumber + " vc " + column); foreach (VisualLineElement element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in WPF device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (this.Document == null) throw ThrowUtil.NoDocumentAssigned(); DocumentLine documentLine = this.Document.GetLineByNumber(position.Line); VisualLine visualLine = GetOrConstructVisualLine(documentLine); int visualColumn = position.VisualColumn; if (visualColumn < 0) { int offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in WPF device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (this.Document == null) throw ThrowUtil.NoDocumentAssigned(); VisualLine line = GetVisualLineFromVisualTop(visualPosition.Y); if (line == null) return null; int visualColumn = line.GetVisualColumn(visualPosition); int documentOffset = line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; return new TextViewPosition(document.GetLocation(documentOffset), visualColumn); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in WPF device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (this.Document == null) throw ThrowUtil.NoDocumentAssigned(); VisualLine line = GetVisualLineFromVisualTop(visualPosition.Y); if (line == null) return null; int visualColumn = line.GetVisualColumnFloor(visualPosition); int documentOffset = line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; return new TextViewPosition(document.GetLocation(documentOffset), visualColumn); } #endregion #region Service Provider readonly ServiceContainer services = new ServiceContainer(); /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> public ServiceContainer Services { get { return services; } } object IServiceProvider.GetService(Type serviceType) { return services.GetService(serviceType); } void ConnectToTextView(object obj) { ITextViewConnect c = obj as ITextViewConnect; if (c != null) c.AddToTextView(this); } void DisconnectFromTextView(object obj) { ITextViewConnect c = obj as ITextViewConnect; if (c != null) c.RemoveFromTextView(this); } #endregion #region MouseHover /// <summary> /// The PreviewMouseHover event. /// </summary> public static readonly RoutedEvent PreviewMouseHoverEvent = EventManager.RegisterRoutedEvent("PreviewMouseHover", RoutingStrategy.Tunnel, typeof(MouseEventHandler), typeof(TextView)); /// <summary> /// The MouseHover event. /// </summary> public static readonly RoutedEvent MouseHoverEvent = EventManager.RegisterRoutedEvent("MouseHover", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(TextView)); /// <summary> /// The PreviewMouseHoverStopped event. /// </summary> public static readonly RoutedEvent PreviewMouseHoverStoppedEvent = EventManager.RegisterRoutedEvent("PreviewMouseHoverStopped", RoutingStrategy.Tunnel, typeof(MouseEventHandler), typeof(TextView)); /// <summary> /// The MouseHoverStopped event. /// </summary> public static readonly RoutedEvent MouseHoverStoppedEvent = EventManager.RegisterRoutedEvent("MouseHoverStopped", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(TextView)); /// <summary> /// Occurs when the mouse has hovered over a fixed location for some time. /// </summary> public event MouseEventHandler PreviewMouseHover { add { AddHandler(PreviewMouseHoverEvent, value); } remove { RemoveHandler(PreviewMouseHoverEvent, value); } } /// <summary> /// Occurs when the mouse has hovered over a fixed location for some time. /// </summary> public event MouseEventHandler MouseHover { add { AddHandler(MouseHoverEvent, value); } remove { RemoveHandler(MouseHoverEvent, value); } } /// <summary> /// Occurs when the mouse had previously hovered but now started moving again. /// </summary> public event MouseEventHandler PreviewMouseHoverStopped { add { AddHandler(PreviewMouseHoverStoppedEvent, value); } remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); } } /// <summary> /// Occurs when the mouse had previously hovered but now started moving again. /// </summary> public event MouseEventHandler MouseHoverStopped { add { AddHandler(MouseHoverStoppedEvent, value); } remove { RemoveHandler(MouseHoverStoppedEvent, value); } } MouseHoverLogic hoverLogic; void RaiseHoverEventPair(MouseEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { var mouseDevice = e.MouseDevice; var stylusDevice = e.StylusDevice; int inputTime = Environment.TickCount; var args1 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) { RoutedEvent = tunnelingEvent, Source = this }; RaiseEvent(args1); var args2 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) { RoutedEvent = bubblingEvent, Source = this, Handled = args1.Handled }; RaiseEvent(args2); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight { get { // return 0 if there is no document = no heightTree return heightTree != null ? heightTree.TotalHeight : 0; } } /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (TextFormatterFactory.PropertyChangeAffectsTextFormatter(e.Property)) { // first, create the new text formatter: RecreateTextFormatter(); // changing text formatter requires recreating the cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); } else if (e.Property == Control.ForegroundProperty || e.Property == TextView.NonPrintableCharacterBrushProperty || e.Property == TextView.LinkTextBackgroundBrushProperty || e.Property == TextView.LinkTextForegroundBrushProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (e.Property == Control.FontFamilyProperty || e.Property == Control.FontSizeProperty || e.Property == Control.FontStretchProperty || e.Property == Control.FontStyleProperty || e.Property == Control.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (e.Property == ColumnRulerPenProperty) { columnRulerRenderer.SetRuler(this.Options.ColumnRulerPosition, this.ColumnRulerPen); } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> /// </summary> public static readonly DependencyProperty ColumnRulerPenProperty = DependencyProperty.Register("ColumnRulerBrush", typeof(Pen), typeof(TextView), new FrameworkPropertyMetadata(CreateFrozenPen(Brushes.LightGray))); static Pen CreateFrozenPen(SolidColorBrush brush) { Pen pen = new Pen(brush, 1); pen.Freeze(); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> /// </summary> public Pen ColumnRulerPen { get { return (Pen)GetValue(ColumnRulerPenProperty); } set { SetValue(ColumnRulerPenProperty, value); } } } }