Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10065450
<NME> TextArea.cs <BEF> // 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private EventHandler _scrollInvalidated; #region Constructor static TextArea() #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed 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; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } internal void OnTextCopied(TextEventArgs e) || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } public void RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } } set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge pull request #106 from Deadpikle/fix/105 Use logical scrollable to invalidate scroll in TextArea <DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; - private EventHandler _scrollInvalidated; #region Constructor static TextArea() @@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing event EventHandler ILogicalScrollable.ScrollInvalidated { - add => _scrollInvalidated += value; - remove => _scrollInvalidated -= value; + add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } + remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) @@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing public void RaiseScrollInvalidated(EventArgs e) { - _scrollInvalidated?.Invoke(this, e); + _logicalScrollable?.RaiseScrollInvalidated(e); } }
3
Merge pull request #106 from Deadpikle/fix/105
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065451
<NME> TextArea.cs <BEF> // 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private EventHandler _scrollInvalidated; #region Constructor static TextArea() #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed 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; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } internal void OnTextCopied(TextEventArgs e) || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } public void RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } } set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge pull request #106 from Deadpikle/fix/105 Use logical scrollable to invalidate scroll in TextArea <DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; - private EventHandler _scrollInvalidated; #region Constructor static TextArea() @@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing event EventHandler ILogicalScrollable.ScrollInvalidated { - add => _scrollInvalidated += value; - remove => _scrollInvalidated -= value; + add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } + remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) @@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing public void RaiseScrollInvalidated(EventArgs e) { - _scrollInvalidated?.Invoke(this, e); + _logicalScrollable?.RaiseScrollInvalidated(e); } }
3
Merge pull request #106 from Deadpikle/fix/105
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065452
<NME> TextArea.cs <BEF> // 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private EventHandler _scrollInvalidated; #region Constructor static TextArea() #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed 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; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } internal void OnTextCopied(TextEventArgs e) || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } public void RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } } set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge pull request #106 from Deadpikle/fix/105 Use logical scrollable to invalidate scroll in TextArea <DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; - private EventHandler _scrollInvalidated; #region Constructor static TextArea() @@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing event EventHandler ILogicalScrollable.ScrollInvalidated { - add => _scrollInvalidated += value; - remove => _scrollInvalidated -= value; + add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } + remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) @@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing public void RaiseScrollInvalidated(EventArgs e) { - _scrollInvalidated?.Invoke(this, e); + _logicalScrollable?.RaiseScrollInvalidated(e); } }
3
Merge pull request #106 from Deadpikle/fix/105
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065453
<NME> TextArea.cs <BEF> // 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private EventHandler _scrollInvalidated; #region Constructor static TextArea() #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed 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; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } internal void OnTextCopied(TextEventArgs e) || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } public void RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } } set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge pull request #106 from Deadpikle/fix/105 Use logical scrollable to invalidate scroll in TextArea <DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; - private EventHandler _scrollInvalidated; #region Constructor static TextArea() @@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing event EventHandler ILogicalScrollable.ScrollInvalidated { - add => _scrollInvalidated += value; - remove => _scrollInvalidated -= value; + add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } + remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) @@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing public void RaiseScrollInvalidated(EventArgs e) { - _scrollInvalidated?.Invoke(this, e); + _logicalScrollable?.RaiseScrollInvalidated(e); } }
3
Merge pull request #106 from Deadpikle/fix/105
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065454
<NME> TextArea.cs <BEF> // 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private EventHandler _scrollInvalidated; #region Constructor static TextArea() #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed 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; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } internal void OnTextCopied(TextEventArgs e) || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } public void RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } } set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge pull request #106 from Deadpikle/fix/105 Use logical scrollable to invalidate scroll in TextArea <DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; - private EventHandler _scrollInvalidated; #region Constructor static TextArea() @@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing event EventHandler ILogicalScrollable.ScrollInvalidated { - add => _scrollInvalidated += value; - remove => _scrollInvalidated -= value; + add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } + remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) @@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing public void RaiseScrollInvalidated(EventArgs e) { - _scrollInvalidated?.Invoke(this, e); + _logicalScrollable?.RaiseScrollInvalidated(e); } }
3
Merge pull request #106 from Deadpikle/fix/105
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065455
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). ```javascript // define a dependency bundle loadjs(['foo.js', 'bar.js'], 'foobar'); // execute code elsewhere when the bundle has loaded loadjs.ready('foobar', function() { loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) You can also use it as a CJS or AMD module. ## Browser Support The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) ```javascript // load a single file loadjs('foo.js', function() { // foo.js loaded }); // load multiple files (in parallel) loadjs(['foo.js', 'bar.js'], function() { // foo.js & bar.js loaded }); // load multiple files (in series) loadjs('foo.js', function() { loadjs('bar.js', function() { // foo.js loaded then bar.js loaded }); }); // add a bundle id loadjs(['foo.js', 'bar.js'], 'foobar', function() { // foo.js & bar.js loaded }); // add a failure callback loadjs(['foo.js', 'bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }, function(pathsNotFound) { /* at least one path didn't load */ }); // execute a callback after bundle finishes loading loadjs(['foo.js', 'bar.js'], 'foobar'); loadjs.ready('foobar', function() { // foo.js & bar.js loaded // .ready() can be chained together loadjs('foo.js', 'foo'); loadjs('bar.js', 'bar'); loadjs .ready('foo', function() { ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` // compose more complex dependency lists loadjs('foo.js', 'foo'); loadjs('bar.js', 'bar'); loadjs(['thunkor.js', 'thunky.js'], 'thunk'); // wait for multiple depdendencies 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -17,7 +17,7 @@ Here's an example of what you can do with LoadJS: ```javascript // define a dependency bundle -loadjs(['foo.js', 'bar.js'], 'foobar'); +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); // execute code elsewhere when the bundle has loaded loadjs.ready('foobar', function() { @@ -29,7 +29,21 @@ The latest version of LoadJS can be found in the `dist/` directory in this repos * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) -You can also use it as a CJS or AMD module. +You can also use it as a CJS or AMD module: + +```bash +$ npm install --save-dev loadjs +``` + +```javascript +var loadjs = require('loadjs'); + +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); + +loadjs.ready('foobar', function() { + // foo.js & bar.js loaded +}); +``` ## Browser Support @@ -45,40 +59,40 @@ You can also use it as a CJS or AMD module. ```javascript // load a single file -loadjs('foo.js', function() { +loadjs('/path/to/foo.js', function() { // foo.js loaded }); // load multiple files (in parallel) -loadjs(['foo.js', 'bar.js'], function() { +loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { // foo.js & bar.js loaded }); // load multiple files (in series) -loadjs('foo.js', function() { - loadjs('bar.js', function() { +loadjs('/path/to/foo.js', function() { + loadjs('/path/to/bar.js', function() { // foo.js loaded then bar.js loaded }); }); // add a bundle id -loadjs(['foo.js', 'bar.js'], 'foobar', function() { +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { // foo.js & bar.js loaded }); // add a failure callback -loadjs(['foo.js', 'bar.js'], +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }, function(pathsNotFound) { /* at least one path didn't load */ }); // execute a callback after bundle finishes loading -loadjs(['foo.js', 'bar.js'], 'foobar'); +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { // foo.js & bar.js loaded @@ -86,8 +100,8 @@ loadjs.ready('foobar', function() { // .ready() can be chained together -loadjs('foo.js', 'foo'); -loadjs('bar.js', 'bar'); +loadjs('/path/to/foo.js', 'foo'); +loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { @@ -99,9 +113,9 @@ loadjs // compose more complex dependency lists -loadjs('foo.js', 'foo'); -loadjs('bar.js', 'bar'); -loadjs(['thunkor.js', 'thunky.js'], 'thunk'); +loadjs('/path/to/foo.js', 'foo'); +loadjs('/path/to/bar.js', 'bar'); +loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies
28
Update README.md
14
.md
md
mit
muicss/loadjs
10065456
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). ```javascript // define a dependency bundle loadjs(['foo.js', 'bar.js'], 'foobar'); // execute code elsewhere when the bundle has loaded loadjs.ready('foobar', function() { loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) You can also use it as a CJS or AMD module. ## Browser Support The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) ```javascript // load a single file loadjs('foo.js', function() { // foo.js loaded }); // load multiple files (in parallel) loadjs(['foo.js', 'bar.js'], function() { // foo.js & bar.js loaded }); // load multiple files (in series) loadjs('foo.js', function() { loadjs('bar.js', function() { // foo.js loaded then bar.js loaded }); }); // add a bundle id loadjs(['foo.js', 'bar.js'], 'foobar', function() { // foo.js & bar.js loaded }); // add a failure callback loadjs(['foo.js', 'bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }, function(pathsNotFound) { /* at least one path didn't load */ }); // execute a callback after bundle finishes loading loadjs(['foo.js', 'bar.js'], 'foobar'); loadjs.ready('foobar', function() { // foo.js & bar.js loaded // .ready() can be chained together loadjs('foo.js', 'foo'); loadjs('bar.js', 'bar'); loadjs .ready('foo', function() { ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` // compose more complex dependency lists loadjs('foo.js', 'foo'); loadjs('bar.js', 'bar'); loadjs(['thunkor.js', 'thunky.js'], 'thunk'); // wait for multiple depdendencies 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -17,7 +17,7 @@ Here's an example of what you can do with LoadJS: ```javascript // define a dependency bundle -loadjs(['foo.js', 'bar.js'], 'foobar'); +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); // execute code elsewhere when the bundle has loaded loadjs.ready('foobar', function() { @@ -29,7 +29,21 @@ The latest version of LoadJS can be found in the `dist/` directory in this repos * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) -You can also use it as a CJS or AMD module. +You can also use it as a CJS or AMD module: + +```bash +$ npm install --save-dev loadjs +``` + +```javascript +var loadjs = require('loadjs'); + +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); + +loadjs.ready('foobar', function() { + // foo.js & bar.js loaded +}); +``` ## Browser Support @@ -45,40 +59,40 @@ You can also use it as a CJS or AMD module. ```javascript // load a single file -loadjs('foo.js', function() { +loadjs('/path/to/foo.js', function() { // foo.js loaded }); // load multiple files (in parallel) -loadjs(['foo.js', 'bar.js'], function() { +loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { // foo.js & bar.js loaded }); // load multiple files (in series) -loadjs('foo.js', function() { - loadjs('bar.js', function() { +loadjs('/path/to/foo.js', function() { + loadjs('/path/to/bar.js', function() { // foo.js loaded then bar.js loaded }); }); // add a bundle id -loadjs(['foo.js', 'bar.js'], 'foobar', function() { +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { // foo.js & bar.js loaded }); // add a failure callback -loadjs(['foo.js', 'bar.js'], +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }, function(pathsNotFound) { /* at least one path didn't load */ }); // execute a callback after bundle finishes loading -loadjs(['foo.js', 'bar.js'], 'foobar'); +loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { // foo.js & bar.js loaded @@ -86,8 +100,8 @@ loadjs.ready('foobar', function() { // .ready() can be chained together -loadjs('foo.js', 'foo'); -loadjs('bar.js', 'bar'); +loadjs('/path/to/foo.js', 'foo'); +loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { @@ -99,9 +113,9 @@ loadjs // compose more complex dependency lists -loadjs('foo.js', 'foo'); -loadjs('bar.js', 'bar'); -loadjs(['thunkor.js', 'thunky.js'], 'thunk'); +loadjs('/path/to/foo.js', 'foo'); +loadjs('/path/to/bar.js', 'bar'); +loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies
28
Update README.md
14
.md
md
mit
muicss/loadjs
10065457
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065458
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065459
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065460
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065461
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065462
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065463
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065464
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065465
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065466
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065467
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065468
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065469
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065470
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065471
<NME> Caret.cs <BEF> // 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.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Threading; namespace AvaloniaEdit.Editing { /// <summary> /// Helper class with caret-related methods. /// </summary> public sealed class Caret { private const double CaretWidth = 0.5; private readonly TextArea _textArea; private readonly TextView _textView; private readonly CaretLayer _caretAdorner; private bool _visible; internal Caret(TextArea textArea) { _textArea = textArea; _textView = textArea.TextView; _position = new TextViewPosition(1, 1, 0); _caretAdorner = new CaretLayer(textArea); _textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); _textView.VisualLinesChanged += TextView_VisualLinesChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } internal void UpdateIfVisible() { if (_visible) { Show(); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { if (_visible) { Show(); } // required because the visual columns might have changed if the // element generators did something differently than on the last run // (e.g. a FoldingSection was collapsed) InvalidateVisualColumn(); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { _caretAdorner?.InvalidateVisual(); } private TextViewPosition _position; /// <summary> /// Gets/Sets the position of the caret. /// Retrieving this property will validate the visual column (which can be expensive). /// Use the <see cref="Location"/> property instead if you don't need the visual column. /// </summary> public TextViewPosition Position { get { ValidateVisualColumn(); return _position; } set { if (_position != value) { _position = value; _storedCaretOffset = -1; ValidatePosition(); InvalidateVisualColumn(); RaisePositionChanged(); Log("Caret position changed to " + value); if (_visible) Show(); } } } /// <summary> /// Gets the caret position without validating it. /// </summary> internal TextViewPosition NonValidatedPosition => _position; /// <summary> /// Gets/Sets the location of the caret. /// The getter of this property is faster than <see cref="Position"/> because it doesn't have /// to validate the visual column. /// </summary> public TextLocation Location { get => _position.Location; set => Position = new TextViewPosition(value); } /// <summary> /// Gets/Sets the caret line. /// </summary> public int Line { get => _position.Line; set => Position = new TextViewPosition(value, _position.Column); } /// <summary> /// Gets/Sets the caret column. /// </summary> public int Column { get => _position.Column; set => Position = new TextViewPosition(_position.Line, value); } /// <summary> /// Gets/Sets the caret visual column. /// </summary> public int VisualColumn { get { ValidateVisualColumn(); return _position.VisualColumn; } set => Position = new TextViewPosition(_position.Line, _position.Column, value); } private bool _isInVirtualSpace; /// <summary> /// Gets whether the caret is in virtual space. /// </summary> public bool IsInVirtualSpace { get { ValidateVisualColumn(); return _isInVirtualSpace; } } private int _storedCaretOffset; internal void OnDocumentChanging() { _storedCaretOffset = Offset; InvalidateVisualColumn(); } internal void OnDocumentChanged(DocumentChangeEventArgs e) { InvalidateVisualColumn(); if (_storedCaretOffset >= 0) { // If the caret is at the end of a selection, we don't expand the selection if something // is inserted at the end. Thus we also need to keep the caret in front of the insertion. AnchorMovementType caretMovementType; if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset) caretMovementType = AnchorMovementType.BeforeInsertion; else caretMovementType = AnchorMovementType.Default; var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType); var document = _textArea.Document; if (document != null) { // keep visual column Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn); } } _storedCaretOffset = -1; } /// <summary> /// Gets/Sets the caret offset. /// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN. /// </summary> public int Offset { get { var document = _textArea.Document; if (document == null) { return 0; } return document.GetOffset(_position.Location); } set { var document = _textArea.Document; if (document != null) { Position = new TextViewPosition(document.GetLocation(value)); DesiredXPos = double.NaN; } } } /// <summary> /// Gets/Sets the desired x-position of the caret, in device-independent pixels. /// This property is NaN if the caret has no desired position. /// </summary> public double DesiredXPos { get; set; } = double.NaN; private void ValidatePosition() { if (_position.Line < 1) _position.Line = 1; if (_position.Column < 1) _position.Column = 1; if (_position.VisualColumn < -1) _position.VisualColumn = -1; var document = _textArea.Document; if (document != null) { if (_position.Line > document.LineCount) { _position.Line = document.LineCount; _position.Column = document.GetLineByNumber(_position.Line).Length + 1; _position.VisualColumn = -1; } else { var line = document.GetLineByNumber(_position.Line); if (_position.Column > line.Length + 1) { _position.Column = line.Length + 1; _position.VisualColumn = -1; } } } } /// <summary> /// Event raised when the caret position has changed. /// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls), /// the PositionChanged event is raised only once at the end of the document update. /// </summary> public event EventHandler PositionChanged; private bool _raisePositionChangedOnUpdateFinished; private void RaisePositionChanged() { if (_textArea.Document != null && _textArea.Document.IsInUpdate) { _raisePositionChangedOnUpdateFinished = true; } else { PositionChanged?.Invoke(this, EventArgs.Empty); } } internal void OnDocumentUpdateFinished() { if (_raisePositionChangedOnUpdateFinished) { _raisePositionChangedOnUpdateFinished = false; PositionChanged?.Invoke(this, EventArgs.Empty); } } private bool _visualColumnValid; private void ValidateVisualColumn() { if (!_visualColumnValid) { var document = _textArea.Document; if (document != null) { // Debug.WriteLine("Explicit validation of caret column"); var documentLine = document.GetLineByNumber(_position.Line); RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine)); } } } private void InvalidateVisualColumn() { _visualColumnValid = false; } /// <summary> /// Validates the visual column of the caret using the specified visual line. /// The visual line must contain the caret offset. /// </summary> private void RevalidateVisualColumn(VisualLine visualLine) { if (visualLine == null) throw new ArgumentNullException(nameof(visualLine)); // mark column as validated _visualColumnValid = true; var caretOffset = _textView.Document.GetOffset(_position.Location); var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset; _position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace); // search possible caret positions var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); // If position.VisualColumn was valid, we're done with validation. if (newVisualColumnForwards != _position.VisualColumn) { // also search backwards so that we can pick the better match var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace); if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0) throw ThrowUtil.NoValidCaretPosition(); // determine offsets for new visual column positions int newOffsetForwards; if (newVisualColumnForwards >= 0) newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset; else newOffsetForwards = -1; int newOffsetBackwards; if (newVisualColumnBackwards >= 0) newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset; else newOffsetBackwards = -1; int newVisualColumn, newOffset; // if there's only one valid position, use it if (newVisualColumnForwards < 0) { newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else if (newVisualColumnBackwards < 0) { newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } else { // two valid positions: find the better match if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) { // backwards is better newVisualColumn = newVisualColumnBackwards; newOffset = newOffsetBackwards; } else { // forwards is better newVisualColumn = newVisualColumnForwards; newOffset = newOffsetForwards; } } Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn); } _isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength); } private Rect CalcCaretRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine); var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn); var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); return new Rect(xPos, lineTop, CaretWidth, lineBottom - lineTop); } Rect CalcCaretOverstrikeRectangle(VisualLine visualLine) { if (!_visualColumnValid) { RevalidateVisualColumn(visualLine); } int currentPos = _position.VisualColumn; // The text being overwritten in overstrike mode is everything up to the next normal caret stop int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true); var textLine = visualLine.GetTextLine(currentPos); Rect r; if (currentPos < visualLine.VisualLength) { // If the caret is within the text, use GetTextBounds() for the text being overwritten. // This is necessary to ensure the rectangle is calculated correctly in bidirectional text. var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0]; r = textBounds.Rectangle; var y = r.Y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop); r = r.WithY(y); } else { // If the caret is at the end of the line (or in virtual space), // use the visual X position of currentPos and nextPos (one or more of which will be in virtual space) double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos); double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos); double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop); double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom); r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop); } // If the caret is too small (e.g. in front of zero-width character), ensure it's still visible if (r.Width < CaretWidth) r = r.WithWidth(CaretWidth); return r; } /// <summary> /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. /// </summary> public Rect CalculateCaretRectangle() { if (_textView?.Document != null) { var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line)); return _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); } return Rect.Empty; } /// <summary> /// Minimum distance of the caret to the view border. /// </summary> internal const double MinimumDistanceToViewBorder = 0; /// <summary> /// Scrolls the text view so that the caret is visible. /// </summary> public void BringCaretToView() { BringCaretToView(0); } public void BringCaretToView(double border) { var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } } /// Makes the caret visible and updates its on-screen position. /// </summary> public void Show() { Log("Caret.Show()"); _visible = true; if (!_showScheduled) { _showScheduled = true; Dispatcher.UIThread.Post(ShowInternal); } } private bool _showScheduled; private bool _hasWin32Caret; private void ShowInternal() { _showScheduled = false; // if show was scheduled but caret hidden in the meantime if (!_visible) return; if (_caretAdorner != null && _textView != null) { var visualLine = _textView.GetVisualLine(_position.Line); if (visualLine != null) { var caretRect = _textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine); // TODO: win32 caret // Create Win32 caret so that Windows knows where our managed caret is. This is necessary for // features like 'Follow text editing' in the Windows Magnifier. //if (!hasWin32Caret) { // hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size); //} //if (hasWin32Caret) { // Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset); //} _caretAdorner.Show(caretRect); //textArea.ime.UpdateCompositionWindow(); } else { _caretAdorner.Hide(); } } } /// <summary> /// Makes the caret invisible. /// </summary> public void Hide() { Log("Caret.Hide()"); _visible = false; if (_hasWin32Caret) { // TODO: win32 caret //Win32.DestroyCaret(); _hasWin32Caret = false; } _caretAdorner?.Hide(); } [Conditional("DEBUG")] private static void Log(string text) { // commented out to make debug output less noisy - add back if there are any problems with the caret //Debug.WriteLine(text); } /// <summary> /// Gets/Sets the color of the caret. /// </summary> public IBrush CaretBrush { get => _caretAdorner.CaretBrush; set => _caretAdorner.CaretBrush = value; } } } <MSG> fix BringCaretToView with border <DFF> @@ -469,7 +469,7 @@ namespace AvaloniaEdit.Editing var caretRectangle = CalculateCaretRectangle(); if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border); + caretRectangle = caretRectangle.Inflate(border); _textView.MakeVisible(caretRectangle); } }
1
fix BringCaretToView with border
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065472
<NME> README.md <BEF> # Node-TimSort: Fast Sorting for Node.js [![Build Status](https://travis-ci.org/mziccard/node-timsort.svg?branch=master)](https://travis-ci.org/mziccard/node-timsort) [![npm version](https://badge.fury.io/js/timsort.svg)](https://www.npmjs.com/package/timsort) An adaptive and **stable** sort algorithm based on merging that requires fewer than nlog(n) comparisons when run on partially sorted arrays. The algorithm uses O(n) memory and still runs in O(nlogn) (worst case) on random arrays. This implementation is based on the original [TimSort](http://svn.python.org/projects/python/trunk/Objects/listsort.txt) developed by Tim Peters for Python's lists (code [here](http://svn.python.org/projects/python/trunk/Objects/listobject.c)). TimSort has been also adopted in Java starting from version 7. ## Acknowledgments - @novacrazy: ported the module to ES6/ES7 and made it available via bower - @kasperisager: implemented faster lexicographic comparison of small integers ## Usage Install the package with npm: ``` npm install --save timsort var arr = [...]; TimSort.sort(arr); ``` Thanks to [@novacrazy](https://github.com/novacrazy) As `array.sort()` by default the `timsort` module sorts according to lexicographical order. You can also provide your own compare function (to sort any object) as: bower install timsort ``` As `array.sort()` by default the `timsort` module sorts according to lexicographical order. You can also provide your own compare function (to sort any object) as: ```javascript function numberCompare(a,b) { return a-b; } var arr = [...]; var TimSort = require('timsort'); TimSort.sort(arr, numberCompare); ``` You can also sort only a specific subrange of the array: ```javascript TimSort.sort(arr, 5, 10); TimSort.sort(arr, numberCompare, 5, 10); ``` ## Performance A benchmark is provided in `benchmark/index.js`. It compares the `timsort` module against the default `array.sort` method in the numerical sorting of different types of integer array (as described [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt)): - *Random array* - *Descending array* - *Ascending array* - *Ascending array with 3 random exchanges* - *Ascending array with 10 random numbers in the end* - *Array of equal elements* - *Random Array with many duplicates* - *Random Array with some duplicates* For any of the array types the sorting is repeated several times and for different array sizes, average execution time is then printed. I run the benchmark on Node v6.3.1 (both pre-compiled and compiled from source, results are very similar), obtaining the following values: <table> <tr> <th></th><th></th> <th colspan="2">Execution Time (ns)</th> <th rowspan="2">Speedup</th> </tr> <tr> <th>Array Type</th> <th>Length</th> <th>TimSort.sort</th> <th>array.sort</th> </tr> <tbody> <tr> <td rowspan="4">Random</td><td>10</td><td>404</td><td>1583</td><td>3.91</td> </tr> <tr> <td>100</td><td>7147</td><td>4442</td><td>0.62</td> </tr> <tr> <td>1000</td><td>96395</td><td>59979</td><td>0.62</td> </tr> <tr> <td>10000</td><td>1341044</td><td>6098065</td><td>4.55</td> </tr> <tr> <td rowspan="4">Descending</td><td>10</td><td>180</td><td>1881</td><td>10.41</td> </tr> <tr> <td>100</td><td>682</td><td>19210</td><td>28.14</td> </tr> <tr> <td>1000</td><td>3809</td><td>185185</td><td>48.61</td> </tr> <tr> <td>10000</td><td>35878</td><td>5392428</td><td>150.30</td> </tr> <tr> <td rowspan="4">Ascending</td><td>10</td><td>173</td><td>816</td><td>4.69</td> </tr> <tr> <td>100</td><td>578</td><td>18147</td><td>31.34</td> </tr> <tr> <td>1000</td><td>2551</td><td>331993</td><td>130.12</td> </tr> <tr> <td>10000</td><td>22098</td><td>5382446</td><td>243.57</td> </tr> <tr> <td rowspan="4">Ascending + 3 Rand Exc</td><td>10</td><td>232</td><td>927</td><td>3.99</td> </tr> <tr> <td>100</td><td>1059</td><td>15792</td><td>14.90</td> </tr> <tr> <td>1000</td><td>3525</td><td>300708</td><td>85.29</td> </tr> <tr> <td>10000</td><td>27455</td><td>4781370</td><td>174.15</td> </tr> <tr> <td rowspan="4">Ascending + 10 Rand End</td><td>10</td><td>378</td><td>1425</td><td>3.77</td> </tr> <tr> <td>100</td><td>1707</td><td>23346</td><td>13.67</td> </tr> <tr> <td>1000</td><td>5818</td><td>334744</td><td>57.53</td> </tr> <tr> <td>10000</td><td>38034</td><td>4985473</td><td>131.08</td> </tr> <tr> <td rowspan="4">Equal Elements</td><td>10</td><td>164</td><td>766</td><td>4.68</td> </tr> <tr> <td>100</td><td>520</td><td>3188</td><td>6.12</td> </tr> <tr> <td>1000</td><td>2340</td><td>27971</td><td>11.95</td> </tr> <tr> <td>10000</td><td>17011</td><td>281672</td><td>16.56</td> </tr> <tr> <td rowspan="4">Many Repetitions</td><td>10</td><td>396</td><td>1482</td><td>3.74</td> </tr> <tr> <td>100</td><td>7282</td><td>25267</td><td>3.47</td> </tr> <tr> <td>1000</td><td>105528</td><td>420120</td><td>3.98</td> </tr> <tr> <td>10000</td><td>1396120</td><td>5787399</td><td>4.15</td> </tr> <tr> <td rowspan="4">Some Repetitions</td><td>10</td><td>390</td><td>1463</td><td>3.75</td> </tr> <tr> <td>100</td><td>6678</td><td>20082</td><td>3.01</td> </tr> <tr> <td>1000</td><td>104344</td><td>374103</td><td>3.59</td> </tr> <tr> <td>10000</td><td>1333816</td><td>5474000</td><td>4.10</td> </tr> </tbody> </table> `TimSort.sort` **is faster** than `array.sort` on almost of the tested array types. In general, the more ordered the array is the better `TimSort.sort` performs with respect to `array.sort` (up to 243 times faster on already sorted arrays). And also, in general, the bigger the array the more we benefit from using the `timsort` module. These data strongly depend on Node.js version and the machine on which the benchmark is run. I strongly encourage you to run the benchmark on your own setup with: ``` npm run benchmark ``` Please also notice that: - This benchmark is far from exhaustive. Several cases are not considered and the results must be taken as partial - *inlining* is surely playing an active role in `timsort` module's good performance - A more accurate comparison of the algorithms would require implementing `array.sort` in pure javascript and counting element comparisons ## Stability TimSort is *stable* which means that equal items maintain their relative order after sorting. Stability is a desirable property for a sorting algorithm. Consider the following array of items with an height and a weight. ```javascript [ { height: 100, weight: 80 }, { height: 90, weight: 90 }, { height: 70, weight: 95 }, { height: 100, weight: 100 }, { height: 80, weight: 110 }, { height: 110, weight: 115 }, { height: 100, weight: 120 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 100, weight: 135 }, { height: 75, weight: 140 }, { height: 70, weight: 140 } ] ``` Items are already sorted by `weight`. Sorting the array according to the item's `height` with the `timsort` module results in the following array: ```javascript [ { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 70, weight: 140 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 80 }, { height: 100, weight: 100 }, { height: 100, weight: 120 }, { height: 100, weight: 135 }, { height: 110, weight: 115 } ] ``` Items with the same `height` are still sorted by `weight` which means they preserved their relative order. `array.sort`, instead, is not guarranteed to be *stable*. In Node v0.12.7 sorting the previous array by `height` with `array.sort` results in: ```javascript [ { height: 70, weight: 140 }, { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 100 }, { height: 100, weight: 80 }, { height: 100, weight: 135 }, { height: 100, weight: 120 }, { height: 110, weight: 115 } ] ``` As you can see the sorting did not preserve `weight` ordering for items with the same `height`. <MSG> Fixed truncated README <DFF> @@ -24,7 +24,10 @@ var TimSort = require('timsort'); var arr = [...]; TimSort.sort(arr); ``` -Thanks to [@novacrazy](https://github.com/novacrazy) +Thanks to [@novacrazy](https://github.com/novacrazy) you can also install the package with bower by running: +``` +bower install timsort +``` As `array.sort()` by default the `timsort` module sorts according to lexicographical order. You can also provide your own compare function (to sort any object) as:
4
Fixed truncated README
1
.md
md
mit
mziccard/node-timsort
10065473
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065474
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065475
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065476
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065477
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065478
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065479
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065480
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065481
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065482
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065483
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065484
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065485
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065486
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065487
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted configuration in solution file <DFF> @@ -58,14 +58,6 @@ Global {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Debug|x64.Build.0 = Debug|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|Any CPU.Build.0 = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.ActiveCfg = Release|Any CPU - {BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
0
Remove unwanted configuration in solution file
8
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10065488
<NME> jsgrid.field.tests.js <BEF> $(function() { var Grid = jsGrid.Grid; module("common field config", { setup: function() { this.isFieldExcluded = function(FieldClass) { return FieldClass === jsGrid.ControlField; }; } }); test("filtering=false prevents rendering filter template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ filtering: false }); equal(field.filterTemplate(), "", "empty filter template for field " + name); }); }); test("inserting=false prevents rendering insert template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ inserting: false }); equal(field.insertTemplate(), "", "empty insert template for field " + name); }); }); test("editing=false renders itemTemplate", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var item = { field: "test" }; var args; var field = new FieldClass({ editing: false, itemTemplate: function() { args = arguments; FieldClass.prototype.itemTemplate.apply(this, arguments); } }); var itemTemplate = field.itemTemplate("test", item); var editTemplate = field.editTemplate("test", item); var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate; var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate; equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name); equal(args.length, 2, "passed both arguments for " + name); equal(args[0], "test", "field value passed as a first argument for " + name); equal(args[1], item, "item passed as a second argument for " + name); }); }); module("jsGrid.field"); test("basic", function() { var customSortingFunc = function() { return 1; }, field = new jsGrid.Field({ name: "testField", title: "testTitle", sorter: customSortingFunc }); equal(field.headerTemplate(), "testTitle"); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate(), ""); equal(field.insertTemplate(), ""); equal(field.editTemplate("testValue"), "testValue"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testValue"); strictEqual(field.sortingFunc, customSortingFunc); }); module("jsGrid.field.text"); test("basic", function() { var field = new jsGrid.TextField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); test("set default field options with setDefaults", function() { jsGrid.setDefaults("text", { defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({ fields: [{ type: "text" }] }); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); test("basic", function() { var field = new jsGrid.NumberField({ name: "testField" }); equal(field.itemTemplate(5), "5"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate(6)[0].tagName.toLowerCase(), "input"); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), undefined); strictEqual(field.editValue(), 6); }); module("jsGrid.field.textArea"); test("basic", function() { var field = new jsGrid.TextAreaField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea"); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); module("jsGrid.field.checkbox"); test("basic", function() { var field = new jsGrid.CheckboxField({ name: "testField" }), itemTemplate, filterTemplate, insertTemplate, editTemplate; itemTemplate = field.itemTemplate("testValue"); equal(itemTemplate[0].tagName.toLowerCase(), "input"); equal(itemTemplate.attr("type"), "checkbox"); equal(itemTemplate.attr("disabled"), "disabled"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "input"); equal(filterTemplate.attr("type"), "checkbox"); equal(filterTemplate.prop("indeterminate"), true); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "input"); equal(insertTemplate.attr("type"), "checkbox"); editTemplate = field.editTemplate(true); equal(editTemplate[0].tagName.toLowerCase(), "input"); equal(editTemplate.attr("type"), "checkbox"); equal(editTemplate.is(":checked"), true); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), false); strictEqual(field.editValue(), true); }); module("jsGrid.field.select"); test("basic", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: ["test1", "test2", "test3"], selectedIndex: 1 }); equal(field.itemTemplate(1), "test2"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(2); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(2).is(":selected")); strictEqual(field.filterValue(), 1); strictEqual(field.insertValue(), 1); strictEqual(field.editValue(), 2); }); test("items as array of integers", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: [0, 10, 20], selectedIndex: 0 }); strictEqual(field.itemTemplate(0), 0); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(1); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(1).is(":selected")); strictEqual(field.filterValue(), 0); strictEqual(field.insertValue(), 0); strictEqual(field.editValue(), 1); }); test("string value type", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", valueType: "string", selectedIndex: 1 }); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type auto-defined", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], strictEqual(field.insertValue(), "2"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1" }, { text: "test2", value: "2" } ], textField: "text", valueField: "value" }); strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: 1 }, { text: "test2", value: 2 }, { text: "test3", value: 3 } ] }); strictEqual(field.itemTemplate(1), field.items[1]); field.textField = "text"; strictEqual(field.itemTemplate(1), "test2"); field.textField = ""; field.valueField = "value"; strictEqual(field.itemTemplate(1), field.items[0]); ok(field.editTemplate(2)); strictEqual(field.editValue(), 2); field.textField = "text"; strictEqual(field.itemTemplate(1), "test1"); }); module("jsGrid.field.control"); test("basic", function() { var field, itemTemplate, headerTemplate, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: true, option: $.noop }; itemTemplate = field.itemTemplate("any_value"); equal(itemTemplate.filter("." + field.editButtonClass).length, 1); equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1); headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1); filterTemplate = field.filterTemplate(); equal(filterTemplate.filter("." + field.searchButtonClass).length, 1); equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1); insertTemplate = field.insertTemplate(); equal(insertTemplate.filter("." + field.insertButtonClass).length, 1); editTemplate = field.editTemplate("any_value"); equal(editTemplate.filter("." + field.updateButtonClass).length, 1); equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), ""); }); test("switchMode button should consider filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: true, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered"); deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode"); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode"); }); test("switchMode button should consider inserting=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: false, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered"); deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode"); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode"); }); test("switchMode is not rendered if inserting=false and filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: false }; var headerTemplate = field.headerTemplate(); strictEqual(headerTemplate, "", "empty header"); }); }); <MSG> Fields: Fix select field valueType auto-definition Fixes #311 <DFF> @@ -284,6 +284,20 @@ $(function() { strictEqual(field.insertValue(), "2"); }); + test("value type defaulted to string", function() { + var field = new jsGrid.SelectField({ + name: "testField", + items: [ + { text: "test1" }, + { text: "test2", value: "2" } + ], + textField: "text", + valueField: "value" + }); + + strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); + }); + test("object items", function() { var field = new jsGrid.SelectField({ name: "testField",
14
Fields: Fix select field valueType auto-definition
0
.js
field
mit
tabalinas/jsgrid
10065489
<NME> jsgrid.field.tests.js <BEF> $(function() { var Grid = jsGrid.Grid; module("common field config", { setup: function() { this.isFieldExcluded = function(FieldClass) { return FieldClass === jsGrid.ControlField; }; } }); test("filtering=false prevents rendering filter template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ filtering: false }); equal(field.filterTemplate(), "", "empty filter template for field " + name); }); }); test("inserting=false prevents rendering insert template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ inserting: false }); equal(field.insertTemplate(), "", "empty insert template for field " + name); }); }); test("editing=false renders itemTemplate", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var item = { field: "test" }; var args; var field = new FieldClass({ editing: false, itemTemplate: function() { args = arguments; FieldClass.prototype.itemTemplate.apply(this, arguments); } }); var itemTemplate = field.itemTemplate("test", item); var editTemplate = field.editTemplate("test", item); var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate; var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate; equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name); equal(args.length, 2, "passed both arguments for " + name); equal(args[0], "test", "field value passed as a first argument for " + name); equal(args[1], item, "item passed as a second argument for " + name); }); }); module("jsGrid.field"); test("basic", function() { var customSortingFunc = function() { return 1; }, field = new jsGrid.Field({ name: "testField", title: "testTitle", sorter: customSortingFunc }); equal(field.headerTemplate(), "testTitle"); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate(), ""); equal(field.insertTemplate(), ""); equal(field.editTemplate("testValue"), "testValue"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testValue"); strictEqual(field.sortingFunc, customSortingFunc); }); module("jsGrid.field.text"); test("basic", function() { var field = new jsGrid.TextField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); test("set default field options with setDefaults", function() { jsGrid.setDefaults("text", { defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({ fields: [{ type: "text" }] }); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); test("basic", function() { var field = new jsGrid.NumberField({ name: "testField" }); equal(field.itemTemplate(5), "5"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate(6)[0].tagName.toLowerCase(), "input"); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), undefined); strictEqual(field.editValue(), 6); }); module("jsGrid.field.textArea"); test("basic", function() { var field = new jsGrid.TextAreaField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea"); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); module("jsGrid.field.checkbox"); test("basic", function() { var field = new jsGrid.CheckboxField({ name: "testField" }), itemTemplate, filterTemplate, insertTemplate, editTemplate; itemTemplate = field.itemTemplate("testValue"); equal(itemTemplate[0].tagName.toLowerCase(), "input"); equal(itemTemplate.attr("type"), "checkbox"); equal(itemTemplate.attr("disabled"), "disabled"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "input"); equal(filterTemplate.attr("type"), "checkbox"); equal(filterTemplate.prop("indeterminate"), true); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "input"); equal(insertTemplate.attr("type"), "checkbox"); editTemplate = field.editTemplate(true); equal(editTemplate[0].tagName.toLowerCase(), "input"); equal(editTemplate.attr("type"), "checkbox"); equal(editTemplate.is(":checked"), true); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), false); strictEqual(field.editValue(), true); }); module("jsGrid.field.select"); test("basic", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: ["test1", "test2", "test3"], selectedIndex: 1 }); equal(field.itemTemplate(1), "test2"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(2); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(2).is(":selected")); strictEqual(field.filterValue(), 1); strictEqual(field.insertValue(), 1); strictEqual(field.editValue(), 2); }); test("items as array of integers", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: [0, 10, 20], selectedIndex: 0 }); strictEqual(field.itemTemplate(0), 0); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(1); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(1).is(":selected")); strictEqual(field.filterValue(), 0); strictEqual(field.insertValue(), 0); strictEqual(field.editValue(), 1); }); test("string value type", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", valueType: "string", selectedIndex: 1 }); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type auto-defined", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], strictEqual(field.insertValue(), "2"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1" }, { text: "test2", value: "2" } ], textField: "text", valueField: "value" }); strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: 1 }, { text: "test2", value: 2 }, { text: "test3", value: 3 } ] }); strictEqual(field.itemTemplate(1), field.items[1]); field.textField = "text"; strictEqual(field.itemTemplate(1), "test2"); field.textField = ""; field.valueField = "value"; strictEqual(field.itemTemplate(1), field.items[0]); ok(field.editTemplate(2)); strictEqual(field.editValue(), 2); field.textField = "text"; strictEqual(field.itemTemplate(1), "test1"); }); module("jsGrid.field.control"); test("basic", function() { var field, itemTemplate, headerTemplate, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: true, option: $.noop }; itemTemplate = field.itemTemplate("any_value"); equal(itemTemplate.filter("." + field.editButtonClass).length, 1); equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1); headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1); filterTemplate = field.filterTemplate(); equal(filterTemplate.filter("." + field.searchButtonClass).length, 1); equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1); insertTemplate = field.insertTemplate(); equal(insertTemplate.filter("." + field.insertButtonClass).length, 1); editTemplate = field.editTemplate("any_value"); equal(editTemplate.filter("." + field.updateButtonClass).length, 1); equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), ""); }); test("switchMode button should consider filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: true, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered"); deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode"); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode"); }); test("switchMode button should consider inserting=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: false, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered"); deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode"); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode"); }); test("switchMode is not rendered if inserting=false and filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: false }; var headerTemplate = field.headerTemplate(); strictEqual(headerTemplate, "", "empty header"); }); }); <MSG> Fields: Fix select field valueType auto-definition Fixes #311 <DFF> @@ -284,6 +284,20 @@ $(function() { strictEqual(field.insertValue(), "2"); }); + test("value type defaulted to string", function() { + var field = new jsGrid.SelectField({ + name: "testField", + items: [ + { text: "test1" }, + { text: "test2", value: "2" } + ], + textField: "text", + valueField: "value" + }); + + strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); + }); + test("object items", function() { var field = new jsGrid.SelectField({ name: "testField",
14
Fields: Fix select field valueType auto-definition
0
.js
field
mit
tabalinas/jsgrid
10065490
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065491
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065492
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065493
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065494
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065495
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065496
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065497
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065498
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065499
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065500
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065501
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065502
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065503
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065504
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge branch 'master' into dev <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge branch 'master' into dev
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10065505
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065506
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065507
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065508
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065509
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065510
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065511
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065512
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065513
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065514
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065515
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065516
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065517
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065518
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065519
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } { var id = _theme.GetColorId(color); _brushes[id] = SolidColorBrush.Parse(color); } _transformations?.Clear(); { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Use Immutable brushes for highlighting <DFF> @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Avalonia.Media; +using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; @@ -75,7 +76,7 @@ namespace AvaloniaEdit.TextMate { var id = _theme.GetColorId(color); - _brushes[id] = SolidColorBrush.Parse(color); + _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(color)); } _transformations?.Clear();
2
Use Immutable brushes for highlighting
1
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10065520
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, data = [{ field: "value" }], test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, updateData: function(updatingItem) { updated = true; } } }, }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Add new pre-item edit cancel event. - Add onItemEditCancelling event, tests. - Update README with new event; also added onItemEditing to callback list, which was actually missing. <DFF> @@ -1329,6 +1329,8 @@ $(function() { test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, + cancellingArgs, + cancellingRow, data = [{ field: "value" }], @@ -1351,6 +1353,10 @@ $(function() { updateData: function(updatingItem) { updated = true; } + }, + onItemEditCancelling: function(e) { + cancellingArgs = $.extend(true, {}, e); + cancellingRow = grid.rowByItem(data[0])[0]; } }, @@ -1362,6 +1368,10 @@ $(function() { grid.fields[0].editControl.val("new value"); grid.cancelEdit(); + deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); + equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); + equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); + ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
10
Add new pre-item edit cancel event.
0
.js
tests
mit
tabalinas/jsgrid
10065521
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, data = [{ field: "value" }], test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, updateData: function(updatingItem) { updated = true; } } }, }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Add new pre-item edit cancel event. - Add onItemEditCancelling event, tests. - Update README with new event; also added onItemEditing to callback list, which was actually missing. <DFF> @@ -1329,6 +1329,8 @@ $(function() { test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, + cancellingArgs, + cancellingRow, data = [{ field: "value" }], @@ -1351,6 +1353,10 @@ $(function() { updateData: function(updatingItem) { updated = true; } + }, + onItemEditCancelling: function(e) { + cancellingArgs = $.extend(true, {}, e); + cancellingRow = grid.rowByItem(data[0])[0]; } }, @@ -1362,6 +1368,10 @@ $(function() { grid.fields[0].editControl.val("new value"); grid.cancelEdit(); + deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); + equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); + equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); + ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
10
Add new pre-item edit cancel event.
0
.js
tests
mit
tabalinas/jsgrid
10065522
<NME> jsgrid.field.tests.js <BEF> $(function() { var Grid = jsGrid.Grid; module("common field config", { setup: function() { this.isFieldExcluded = function(FieldClass) { return FieldClass === jsGrid.ControlField; }; } }); test("filtering=false prevents rendering filter template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ filtering: false }); equal(field.filterTemplate(), "", "empty filter template for field " + name); }); }); test("inserting=false prevents rendering insert template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ inserting: false }); equal(field.insertTemplate(), "", "empty insert template for field " + name); }); }); test("editing=false renders itemTemplate", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var item = { field: "test" }; var args; var field = new FieldClass({ editing: false, itemTemplate: function() { args = arguments; FieldClass.prototype.itemTemplate.apply(this, arguments); } }); var itemTemplate = field.itemTemplate("test", item); var editTemplate = field.editTemplate("test", item); var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate; var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate; equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name); equal(args.length, 2, "passed both arguments for " + name); equal(args[0], "test", "field value passed as a first argument for " + name); equal(args[1], item, "item passed as a second argument for " + name); }); }); module("jsGrid.field"); test("basic", function() { var customSortingFunc = function() { return 1; }, field = new jsGrid.Field({ name: "testField", title: "testTitle", sorter: customSortingFunc }); equal(field.headerTemplate(), "testTitle"); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate(), ""); equal(field.insertTemplate(), ""); equal(field.editTemplate("testValue"), "testValue"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testValue"); strictEqual(field.sortingFunc, customSortingFunc); }); module("jsGrid.field.text"); test("basic", function() { var field = new jsGrid.TextField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input"); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); test("basic", function() { var field = new jsGrid.NumberField({ name: "testField" }); strictEqual(field.editValue(), 6); }); module("jsGrid.field.textArea"); test("basic", function() { var field = new jsGrid.TextAreaField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea"); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); module("jsGrid.field.checkbox"); test("basic", function() { var field = new jsGrid.CheckboxField({ name: "testField" }), itemTemplate, filterTemplate, insertTemplate, editTemplate; itemTemplate = field.itemTemplate("testValue"); equal(itemTemplate[0].tagName.toLowerCase(), "input"); equal(itemTemplate.attr("type"), "checkbox"); equal(itemTemplate.attr("disabled"), "disabled"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "input"); equal(filterTemplate.attr("type"), "checkbox"); equal(filterTemplate.prop("indeterminate"), true); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "input"); equal(insertTemplate.attr("type"), "checkbox"); editTemplate = field.editTemplate(true); equal(editTemplate[0].tagName.toLowerCase(), "input"); equal(editTemplate.attr("type"), "checkbox"); equal(editTemplate.is(":checked"), true); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), false); strictEqual(field.editValue(), true); }); module("jsGrid.field.select"); test("basic", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: ["test1", "test2", "test3"], selectedIndex: 1 }); equal(field.itemTemplate(1), "test2"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(2); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(2).is(":selected")); strictEqual(field.filterValue(), 1); strictEqual(field.insertValue(), 1); strictEqual(field.editValue(), 2); }); test("items as array of integers", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: [0, 10, 20], selectedIndex: 0 }); strictEqual(field.itemTemplate(0), 0); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(1); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(1).is(":selected")); strictEqual(field.filterValue(), 0); strictEqual(field.insertValue(), 0); strictEqual(field.editValue(), 1); }); test("string value type", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", valueType: "string", selectedIndex: 1 }); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type auto-defined", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", selectedIndex: 1 }); strictEqual(field.sorter, "string", "sorter set according to value type"); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type defaulted to string", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1" }, { text: "test2", value: "2" } ], textField: "text", valueField: "value" }); strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: 1 }, { text: "test2", value: 2 }, { text: "test3", value: 3 } ] strictEqual(field.itemTemplate(1), "test1"); }); module("jsGrid.field.control"); itemTemplate, headerTemplate, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: true, option: $.noop }; itemTemplate = field.itemTemplate("any_value"); equal(itemTemplate.filter("." + field.editButtonClass).length, 1); equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1); headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1); filterTemplate = field.filterTemplate(); equal(filterTemplate.filter("." + field.searchButtonClass).length, 1); equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1); insertTemplate = field.insertTemplate(); equal(insertTemplate.filter("." + field.insertButtonClass).length, 1); editTemplate = field.editTemplate("any_value"); equal(editTemplate.filter("." + field.updateButtonClass).length, 1); equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), ""); }); test("switchMode button should consider filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: true, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered"); deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode"); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode"); }); test("switchMode button should consider inserting=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: false, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered"); deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode"); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode"); }); test("switchMode is not rendered if inserting=false and filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: false }; var headerTemplate = field.headerTemplate(); strictEqual(headerTemplate, "", "empty header"); }); }); <MSG> Merge pull request #314 from snemarch/feature/insert-default-value Fields: Add support for default value on item insert <DFF> @@ -105,6 +105,13 @@ $(function() { equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); + test("insert default value", function() { + var field = new jsGrid.TextField({ defaultValue: "foo" }); + + field.insertTemplate(); + strictEqual(field.insertValue(), "foo"); + }); + module("jsGrid.field.number"); @@ -120,6 +127,13 @@ $(function() { strictEqual(field.editValue(), 6); }); + test("insert default value", function() { + var field = new jsGrid.NumberField({ defaultValue: 42 }); + + field.insertTemplate(); + strictEqual(field.insertValue(), 42); + }); + module("jsGrid.field.textArea"); @@ -309,6 +323,22 @@ $(function() { strictEqual(field.itemTemplate(1), "test1"); }); + test("insert default value", function() { + var field = new jsGrid.SelectField({ + name: "testField", + items: [ + { text: "test1", value: "foo" }, + { text: "test2", value: "bar" }, + { text: "test3", value: "baz" }, + ], + valueField: "value", + defaultValue: "bar" + }); + + field.insertTemplate(); + equal(field.insertValue(), "bar"); + }); + module("jsGrid.field.control");
30
Merge pull request #314 from snemarch/feature/insert-default-value
0
.js
field
mit
tabalinas/jsgrid
10065523
<NME> jsgrid.field.tests.js <BEF> $(function() { var Grid = jsGrid.Grid; module("common field config", { setup: function() { this.isFieldExcluded = function(FieldClass) { return FieldClass === jsGrid.ControlField; }; } }); test("filtering=false prevents rendering filter template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ filtering: false }); equal(field.filterTemplate(), "", "empty filter template for field " + name); }); }); test("inserting=false prevents rendering insert template", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var field = new FieldClass({ inserting: false }); equal(field.insertTemplate(), "", "empty insert template for field " + name); }); }); test("editing=false renders itemTemplate", function() { var isFieldExcluded = this.isFieldExcluded; $.each(jsGrid.fields, function(name, FieldClass) { if(isFieldExcluded(FieldClass)) return; var item = { field: "test" }; var args; var field = new FieldClass({ editing: false, itemTemplate: function() { args = arguments; FieldClass.prototype.itemTemplate.apply(this, arguments); } }); var itemTemplate = field.itemTemplate("test", item); var editTemplate = field.editTemplate("test", item); var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate; var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate; equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name); equal(args.length, 2, "passed both arguments for " + name); equal(args[0], "test", "field value passed as a first argument for " + name); equal(args[1], item, "item passed as a second argument for " + name); }); }); module("jsGrid.field"); test("basic", function() { var customSortingFunc = function() { return 1; }, field = new jsGrid.Field({ name: "testField", title: "testTitle", sorter: customSortingFunc }); equal(field.headerTemplate(), "testTitle"); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate(), ""); equal(field.insertTemplate(), ""); equal(field.editTemplate("testValue"), "testValue"); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testValue"); strictEqual(field.sortingFunc, customSortingFunc); }); module("jsGrid.field.text"); test("basic", function() { var field = new jsGrid.TextField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "input"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input"); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); module("jsGrid.field.number"); test("basic", function() { var field = new jsGrid.NumberField({ name: "testField" }); strictEqual(field.editValue(), 6); }); module("jsGrid.field.textArea"); test("basic", function() { var field = new jsGrid.TextAreaField({ name: "testField" }); equal(field.itemTemplate("testValue"), "testValue"); equal(field.filterTemplate()[0].tagName.toLowerCase(), "input"); equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea"); equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea"); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), "testEditValue"); }); module("jsGrid.field.checkbox"); test("basic", function() { var field = new jsGrid.CheckboxField({ name: "testField" }), itemTemplate, filterTemplate, insertTemplate, editTemplate; itemTemplate = field.itemTemplate("testValue"); equal(itemTemplate[0].tagName.toLowerCase(), "input"); equal(itemTemplate.attr("type"), "checkbox"); equal(itemTemplate.attr("disabled"), "disabled"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "input"); equal(filterTemplate.attr("type"), "checkbox"); equal(filterTemplate.prop("indeterminate"), true); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "input"); equal(insertTemplate.attr("type"), "checkbox"); editTemplate = field.editTemplate(true); equal(editTemplate[0].tagName.toLowerCase(), "input"); equal(editTemplate.attr("type"), "checkbox"); equal(editTemplate.is(":checked"), true); strictEqual(field.filterValue(), undefined); strictEqual(field.insertValue(), false); strictEqual(field.editValue(), true); }); module("jsGrid.field.select"); test("basic", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: ["test1", "test2", "test3"], selectedIndex: 1 }); equal(field.itemTemplate(1), "test2"); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(2); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(2).is(":selected")); strictEqual(field.filterValue(), 1); strictEqual(field.insertValue(), 1); strictEqual(field.editValue(), 2); }); test("items as array of integers", function() { var field, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.SelectField({ name: "testField", items: [0, 10, 20], selectedIndex: 0 }); strictEqual(field.itemTemplate(0), 0); filterTemplate = field.filterTemplate(); equal(filterTemplate[0].tagName.toLowerCase(), "select"); equal(filterTemplate.children().length, 3); insertTemplate = field.insertTemplate(); equal(insertTemplate[0].tagName.toLowerCase(), "select"); equal(insertTemplate.children().length, 3); editTemplate = field.editTemplate(1); equal(editTemplate[0].tagName.toLowerCase(), "select"); equal(editTemplate.find("option:selected").length, 1); ok(editTemplate.children().eq(1).is(":selected")); strictEqual(field.filterValue(), 0); strictEqual(field.insertValue(), 0); strictEqual(field.editValue(), 1); }); test("string value type", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", valueType: "string", selectedIndex: 1 }); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type auto-defined", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: "1" }, { text: "test2", value: "2" }, { text: "test3", value: "3" } ], textField: "text", valueField: "value", selectedIndex: 1 }); strictEqual(field.sorter, "string", "sorter set according to value type"); field.filterTemplate(); strictEqual(field.filterValue(), "2"); field.editTemplate("2"); strictEqual(field.editValue(), "2"); field.insertTemplate(); strictEqual(field.insertValue(), "2"); }); test("value type defaulted to string", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1" }, { text: "test2", value: "2" } ], textField: "text", valueField: "value" }); strictEqual(field.sorter, "string", "sorter set to string if first item has no value field"); }); test("object items", function() { var field = new jsGrid.SelectField({ name: "testField", items: [ { text: "test1", value: 1 }, { text: "test2", value: 2 }, { text: "test3", value: 3 } ] strictEqual(field.itemTemplate(1), "test1"); }); module("jsGrid.field.control"); itemTemplate, headerTemplate, filterTemplate, insertTemplate, editTemplate; field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: true, option: $.noop }; itemTemplate = field.itemTemplate("any_value"); equal(itemTemplate.filter("." + field.editButtonClass).length, 1); equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1); headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1); filterTemplate = field.filterTemplate(); equal(filterTemplate.filter("." + field.searchButtonClass).length, 1); equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1); insertTemplate = field.insertTemplate(); equal(insertTemplate.filter("." + field.insertButtonClass).length, 1); editTemplate = field.editTemplate("any_value"); equal(editTemplate.filter("." + field.updateButtonClass).length, 1); equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1); strictEqual(field.filterValue(), ""); strictEqual(field.insertValue(), ""); strictEqual(field.editValue(), ""); }); test("switchMode button should consider filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: true, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered"); deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode"); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode"); }); test("switchMode button should consider inserting=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: true, inserting: false, option: function(name, value) { optionArgs = { name: name, value: value }; } }; var headerTemplate = field.headerTemplate(); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered"); var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass); $modeSwitchButton.trigger("click"); ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached"); equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered"); equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered"); deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode"); $modeSwitchButton.trigger("click"); ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached"); deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode"); }); test("switchMode is not rendered if inserting=false and filtering=false", function() { var optionArgs = {}; var field = new jsGrid.ControlField(); field._grid = { filtering: false, inserting: false }; var headerTemplate = field.headerTemplate(); strictEqual(headerTemplate, "", "empty header"); }); }); <MSG> Merge pull request #314 from snemarch/feature/insert-default-value Fields: Add support for default value on item insert <DFF> @@ -105,6 +105,13 @@ $(function() { equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set"); }); + test("insert default value", function() { + var field = new jsGrid.TextField({ defaultValue: "foo" }); + + field.insertTemplate(); + strictEqual(field.insertValue(), "foo"); + }); + module("jsGrid.field.number"); @@ -120,6 +127,13 @@ $(function() { strictEqual(field.editValue(), 6); }); + test("insert default value", function() { + var field = new jsGrid.NumberField({ defaultValue: 42 }); + + field.insertTemplate(); + strictEqual(field.insertValue(), 42); + }); + module("jsGrid.field.textArea"); @@ -309,6 +323,22 @@ $(function() { strictEqual(field.itemTemplate(1), "test1"); }); + test("insert default value", function() { + var field = new jsGrid.SelectField({ + name: "testField", + items: [ + { text: "test1", value: "foo" }, + { text: "test2", value: "bar" }, + { text: "test3", value: "baz" }, + ], + valueField: "value", + defaultValue: "bar" + }); + + field.insertTemplate(); + equal(field.insertValue(), "bar"); + }); + module("jsGrid.field.control");
30
Merge pull request #314 from snemarch/feature/insert-default-value
0
.js
field
mit
tabalinas/jsgrid
10065524
<NME> README.md <BEF> # Lumen Passport [![Build Status](https://travis-ci.org/dusterio/lumen-passport.svg)](https://travis-ci.org/dusterio/lumen-passport) [![Code Climate](https://codeclimate.com/github/dusterio/lumen-passport/badges/gpa.svg)](https://codeclimate.com/github/dusterio/lumen-passport/badges) [![Total Downloads](https://poser.pugx.org/dusterio/lumen-passport/d/total.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Stable Version](https://poser.pugx.org/dusterio/lumen-passport/v/stable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Unstable Version](https://poser.pugx.org/dusterio/lumen-passport/v/unstable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![License](https://poser.pugx.org/dusterio/lumen-passport/license.svg)](https://packagist.org/packages/dusterio/lumen-passport) > Making Laravel Passport work with Lumen ## Introduction It's a simple service provider that makes **Laravel Passport** work with **Lumen**. ## Installation First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet. Then install **Lumen Passport**: ```bash composer require dusterio/lumen-passport ``` Or if you prefer, edit `composer.json` manually and run then `composer update`: ```json { "require": { "dusterio/lumen-passport": "^0.3.5" } } ``` ### Modify the bootstrap flow We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider: ```php /** @file bootstrap/app.php */ // Enable Facades $app->withFacades(); // Enable Eloquent $app->withEloquent(); // Enable auth middleware (shipped with Lumen) $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); // Register two service providers, Laravel Passport and Lumen adapter $app->register(Laravel\Passport\PassportServiceProvider::class); $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` ### Laravel Passport ^7.3.2 and newer On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows: ```php /** @file bootstrap/app.php */ //$app = new Laravel\Lumen\Application( // dirname(__DIR__) //); $app = new \Dusterio\LumenPassport\Lumen7Application( dirname(__DIR__) ); ``` \* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._ ### Migrate and install Laravel Passport ```bash # Create new tables for Passport php artisan migrate # Install encryption keys and other stuff for Passport php artisan passport:install ``` It will output the Personal access client ID and secret, and the Password grand client ID and secret. \* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._ ## Configuration ### Configure Authentication Edit `config/auth.php` to suit your needs. A simple example: ```php /** @file config/auth.php */ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \App\Models\User::class ] ], ]; ``` \* _Note: Lumen 7.x and older uses `\App\User::class`_ Load the config since Lumen doesn't load config files automatically: ```php /** @file bootstrap/app.php */ $app->configure('auth'); ]; ``` ## Registering Routes Next, you should call the LumenPassport::routes method within the boot method of your application (one of your service providers). { public function boot() { LumenPassport::routes($this->app); /* rest of boot */ } } ``` ### User model Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait. ```php /** @file app/Models/User.php */ use Laravel\Passport\HasApiTokens; class User extends Model implements AuthenticatableContract, AuthorizableContract { use HasApiTokens, Authenticatable, Authorizable, HasFactory; /* rest of the model */ } ``` ## Usage You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport). ### Curl example with username and password authentication First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests. ```bash # Request curl --location --request POST '{{APP_URL}}/oauth/token' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type": "password", "client_id": "{{CLIENT_ID}}", "client_secret": "{{CLIENT_SECRET}}", "username": "{{USER_EMAIL}}", "password": "{{USER_PASSWORD}}", "scope": "*" }' ``` ```json { "token_type": "Bearer", "expires_in": 31536000, "access_token": "******", "refresh_token": "******" } ``` And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**. ```php /** @file routes/web.php */ $router->get('/ping', ['middleware' => 'auth', fn () => 'pong']); ``` ```bash # Request curl --location --request GET '{{APP_URL}}/ping' \ --header 'Authorization: Bearer {{ACCESS_TOKEN}}' ``` ```html pong ``` ### Installed routes This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`: Verb | Path | Controller | Action | Middleware --- | --- | --- | --- | --- POST | /oauth/token | AccessTokenController | issueToken | - GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth POST | /oauth/token/refresh | TransientTokenController | refresh | auth GET | /oauth/clients | ClientController | forUser | auth POST | /oauth/clients | ClientController | store | auth PUT | /oauth/clients/{client_id} | ClientController | update | auth DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth GET | /oauth/scopes | ScopeController | all | auth GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth \* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._ ## Extra features There are a couple of extra features that aren't present in **Laravel Passport** ### Prefixing Routes You can add that into an existing group, or add use this route registrar independently like so; ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); /* rest of boot */ } } ``` ### Multiple tokens per client Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers simultaneously. Currently **Laravel Passport** does not allow that. ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); LumenPassport::allowMultipleTokens(); /* rest of boot */ } } ``` ### Different TTLs for different password clients **Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users). Simply do the following in your service provider: ```php /** @file app/Providers/AuthServiceProvider.php */ use Carbon\Carbon; use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); $client_id = '1'; LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id); /* rest of boot */ } } ``` If you don't specify client Id, it will simply fall back to Laravel Passport implementation. ### Purge expired tokens ```bash php artisan passport:purge ``` Simply run it to remove expired refresh tokens and their corresponding access tokens from the database. ## Error and issue resolution Instead of opening a new issue, please see if someone has already had it and it has been resolved. If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md). ## Video tutorials I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps. Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :) ## License The MIT License (MIT) Copyright (c) 2016 Denis Mysenko 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. <MSG> r Readme <DFF> @@ -119,6 +119,12 @@ return [ ]; ``` +Load the config in `bootstrap/app.php` since Lumen doesn't load config files automatically: + +```php +$app->configure('auth'); +``` + ## Registering Routes Next, you should call the LumenPassport::routes method within the boot method of your application (one of your service providers).
6
r Readme
0
.md
md
mit
dusterio/lumen-passport
10065525
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065526
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065527
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065528
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065529
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065530
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065531
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065532
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065533
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065534
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065535
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065536
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065537
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065538
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065539
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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 ( recreate && 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); } MeasureInlineObjects(); 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); 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); //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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private 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); visualLine.RunTransformers(textSource, lineTransformersArray); TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( { var textLine = _formatter.FormatLine( textSource, 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) 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); _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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #257 from AvaloniaUI/reformat-textview Reformat TextView.cs <DFF> @@ -25,6 +25,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; + using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; @@ -37,6 +38,7 @@ using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; + using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; @@ -63,8 +65,8 @@ namespace AvaloniaEdit.Rendering FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - DocumentProperty.Changed.Subscribe(OnDocumentChanged); - } + DocumentProperty.Changed.Subscribe(OnDocumentChanged); + } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; @@ -94,7 +96,7 @@ namespace AvaloniaEdit.Rendering _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } - #endregion + #endregion #region Document Property /// <summary> @@ -433,12 +435,12 @@ namespace AvaloniaEdit.Rendering 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); + /// <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; @@ -652,7 +654,7 @@ namespace AvaloniaEdit.Rendering { changedSomethingBeforeOrInLine = true; - if ( recreate && offset + length >= lineStart) + if (recreate && offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); @@ -743,40 +745,43 @@ namespace AvaloniaEdit.Rendering 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 + /// <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) @@ -855,33 +860,34 @@ namespace AvaloniaEdit.Rendering } #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; + #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; + 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); + /// <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)) + if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } - - _lastAvailableSize = availableSize; - foreach (var layer in Layers) { - layer.Measure(availableSize); - } + _lastAvailableSize = availableSize; + + foreach (var layer in Layers) + { + layer.Measure(availableSize); + } MeasureInlineObjects(); @@ -937,14 +943,14 @@ namespace AvaloniaEdit.Rendering 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); + /// <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); @@ -1013,59 +1019,64 @@ namespace AvaloniaEdit.Rendering private TextFormatter _formatter; internal TextViewCachedElements CachedElements; - private TextRunProperties CreateGlobalTextRunProperties() - { - var p = new GlobalTextRunProperties(); - p.typeface = this.CreateTypeface(); - p.fontRenderingEmSize = FontSize; - p.foregroundBrush = GetValue(TextElement.ForegroundProperty); - ExtensionMethods.CheckIsFrozen(p.foregroundBrush); - p.cultureInfo = CultureInfo.CurrentCulture; - return p; - } - - private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) - { - return new VisualLineTextParagraphProperties { - defaultTextRunProperties = defaultTextRunProperties, - textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, - tabSize = Options.IndentationSize * WideSpaceWidth - }; - } - - private 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?"); - } - } + private TextRunProperties CreateGlobalTextRunProperties() + { + var p = new GlobalTextRunProperties(); + p.typeface = this.CreateTypeface(); + p.fontRenderingEmSize = FontSize; + p.foregroundBrush = GetValue(TextElement.ForegroundProperty); + ExtensionMethods.CheckIsFrozen(p.foregroundBrush); + p.cultureInfo = CultureInfo.CurrentCulture; + return p; + } + + private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) + { + return new VisualLineTextParagraphProperties + { + defaultTextRunProperties = defaultTextRunProperties, + textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, + tabSize = Options.IndentationSize * WideSpaceWidth + }; + } + + private 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); @@ -1073,7 +1084,7 @@ namespace AvaloniaEdit.Rendering TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); - + while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( @@ -1083,38 +1094,41 @@ namespace AvaloniaEdit.Rendering 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.TextLineBreak; - } - visualLine.SetTextLines(textLines); - _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); - return visualLine; - } + // 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.TextLineBreak; + } + visualLine.SetTextLines(textLines); + _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); + return visualLine; + } private static int GetIndentationVisualColumn(VisualLine visualLine) { @@ -1181,18 +1195,18 @@ namespace AvaloniaEdit.Rendering foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; - + if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); - + var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); - + inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } - + offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); @@ -1472,9 +1486,9 @@ namespace AvaloniaEdit.Rendering var line = _formatter.FormatLine(
177
Merge pull request #257 from AvaloniaUI/reformat-textview
163
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065540
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065541
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065542
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065543
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065544
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065545
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065546
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065547
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065548
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065549
<NME> TextView.cs <BEF> // 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 System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; 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.Editing; 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 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, EventArgs.Empty); } 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.Add(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); } _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 private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<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: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var 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.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var 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 (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var 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) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private 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; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); 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; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(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 (var vl in 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)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var 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 device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, 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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <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 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 (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #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 => _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(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Feature/ilogical scrolling (fixes #2) (#6) * Enable vertical scrolling. * internal access modifier to allow scrolloffset data to be set from textarea. * implement ILogicalScrollable interface. * implement working scrolling. * remove debug code. * white space. * Define AdditionalVerticalScrollAmount as a const. * explicit implementations of ILogicalScrollable. * Revert "explicit implementations of ILogicalScrollable." This reverts commit 2bcef08695e3055343690fc583fb9763b97c18c0. * explicit implementations of ILogicalScrolling. <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Feature/ilogical scrolling (fixes #2) (#6)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit