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
10062150
<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. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #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 /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || 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); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; } } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); 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> invalidate margins on scroll. <DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; + + foreach(var margin in LeftMargins) + { + margin.InvalidateVisual(); + } } }
5
invalidate margins on scroll.
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062151
<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. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #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 /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || 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); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; } } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); 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> invalidate margins on scroll. <DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; + + foreach(var margin in LeftMargins) + { + margin.InvalidateVisual(); + } } }
5
invalidate margins on scroll.
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062152
<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. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #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 /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || 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); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; } } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); 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> invalidate margins on scroll. <DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; + + foreach(var margin in LeftMargins) + { + margin.InvalidateVisual(); + } } }
5
invalidate margins on scroll.
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062153
<NME> AccessTokenController.php <BEF> <?php namespace Dusterio\LumenPassport\Http\Controllers; use Laravel\Passport\Passport; use Laravel\Passport\Token; use Laminas\Diactoros\Response as Psr7Response; use Psr\Http\Message\ServerRequestInterface; use Dusterio\LumenPassport\LumenPassport; /** * Class AccessTokenController * @package Dusterio\LumenPassport\Http\Controllers */ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTokenController { /** * Authorize a client to access the user's account. * * @param ServerRequestInterface $request * @return Response */ public function issueToken(ServerRequestInterface $request) { $response = $this->withErrorHandling(function () use ($request) { $input = (array) $request->getParsedBody(); $clientId = isset($input['client_id']) ? $input['client_id'] : null; // Overwrite password grant at the last minute to add support for customized TTLs $this->server->enableGrantType( $this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId) ); return $this->server->respondToAccessTokenRequest($request, new Psr7Response); }); if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) { return $response; } $payload = json_decode($response->getBody()->__toString(), true); if (isset($payload['access_token'])) { /* @deprecated the jwt property will be removed in a future Laravel Passport release */ $token = $this->jwt->parse($payload['access_token']); if (method_exists($token, 'getClaim')) { $tokenId = $token->getClaim('jti'); } else if (method_exists($token, 'claims')) { $tokenId = $token->claims()->get('jti'); } else { throw new \RuntimeException('This package is not compatible to the used Laravel Passport version.'); } $token = $this->tokens->find($tokenId); if (!$token instanceof Token) { return $response; } if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) { // We keep previous tokens for password clients } else { $this->revokeOrDeleteAccessTokens($token, $tokenId); } } return $response; } /** * Create and configure a Password grant instance. * * @return \League\OAuth2\Server\Grant\PasswordGrant */ private function makePasswordGrant() { $grant = new \League\OAuth2\Server\Grant\PasswordGrant( app()->make(\Laravel\Passport\Bridge\UserRepository::class), app()->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class) ); $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn()); return $grant; } /** * Revoke the user's other access tokens for the client. * * @param Token $token * @param string $tokenId * @return void */ protected function revokeOrDeleteAccessTokens(Token $token, $tokenId) { $query = Token::where('user_id', $token->user_id)->where('client_id', $token->client_id); if ($tokenId) { $query->where('id', '<>', $tokenId); } $query->update(['revoked' => true]); } } <MSG> Update AccessTokenController.php <DFF> @@ -48,7 +48,7 @@ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTok } else if (method_exists($token, 'claims')) { $tokenId = $token->claims()->get('jti'); } else { - throw new \RuntimeException('This package is not compatible to the used Laravel Passport version.'); + throw new \RuntimeException('This package is not compatible with the Laravel Passport version used'); } $token = $this->tokens->find($tokenId);
1
Update AccessTokenController.php
1
.php
php
mit
dusterio/lumen-passport
10062154
<NME> introduction.md <BEF> ## Introduction FruitMachine is used to assemble nested views from defined modules. It can be used solely on the client, server (via Node), or both. Unlike other solutions, FruitMachine doesn't try to architect your application for you, it simply provides you with the tools to assemble and communicate with your view modules. #### What is a 'module'? When referring to a module we mean a reusable UI component. For example let's use the common 'tabbed container' component as an example module. Our tabbed container needs some markup, some styling and some basic JavaScript interactions. We might want to use this module in two different places within our app, but we don't want to have to write the markup, the styling or the interaction logic twice. When writing modular components we only have to write things once! #### What is a 'layout'? As far a FruitMachine is concerned there is no difference between layouts and modules, all modules are the same; they are a piece of the UI that has a template, maybe some interaction logic, and perhaps holds some child modules. When we talk about layout modules we are refering to the core page scafolding; a module that usually fills the page, and defines gaps for other modules to sit in. #### Comparisons with the DOM A FruitMachine view is like a simplified DOM tree. Like elements, views have properties, methods and can hold children. There is no limit to how deep a view can become. When an event is fired on a view, it will bubble right to top of the structure, just like DOM events. #### What about my data/models? FruitMachine tries to stay as far away from your data as possible, but of course each module must have data associated with it, and FruitMachine must be able to drop this data into the module's template. FruitMachine comes with it's own Model class (`fruitmachine.Model`) out of the box, just in case you don't have you own; but we have built FruitMachine such that you can use your own types of Model should you wish. FruitMachine just requires you model to have a .`toJSON()` method so that it send its data into the module's template. #### What templating langauge does it use? FruitMachine doesn't care what type of templates you are using, it just expects to be given a function that will return a string. FruitMachine will pass any model data associated with the model as the first argument to this function. This means you can use any templates you like! We like to use [Hogan](http://twitter.github.io/hogan.js/). <MSG> Spelling and flow <DFF> @@ -10,13 +10,13 @@ Our tabbed container needs some markup, some styling and some basic JavaScript i #### What is a 'layout'? -As far a FruitMachine is concerned there is no difference between layouts and modules, all modules are the same; they are a piece of the UI that has a template, maybe some interaction logic, and perhaps holds some child modules. +As far as FruitMachine is concerned there is no difference between layouts and modules, all modules are the same; they are a piece of the UI that has a template, maybe some interaction logic, and perhaps holds some child modules. -When we talk about layout modules we are refering to the core page scafolding; a module that usually fills the page, and defines gaps for other modules to sit in. +When we talk about layout modules we are refering to the core page scaffolding; a module that usually fills the page, and defines gaps for other modules to sit in. #### Comparisons with the DOM -A FruitMachine view is like a simplified DOM tree. Like elements, views have properties, methods and can hold children. There is no limit to how deep a view can become. When an event is fired on a view, it will bubble right to top of the structure, just like DOM events. +A FruitMachine view is like a simplified DOM tree. Like elements, views have properties, methods and can hold children. There is no limit to how deeply nested a set of views can be. When an event is fired on a view, it will bubble right to top of the structure, just like DOM events. #### What about my data/models? @@ -26,4 +26,4 @@ FruitMachine comes with it's own Model class (`FruitMachine.Model`) out of the b #### What templating langauge does it use? -FruitMachine doesn't care what type of templates you are using, it just expects to be given a function that will return a string. FruitMachine will pass any model data associated with the model as the first argument to this function. This means you can use any templates you like! We like to use [Hogan](http://twitter.github.io/hogan.js/). \ No newline at end of file +FruitMachine doesn't care what type of templates you are using, it just expects to be given a function that will return a string. FruitMachine will pass any model data associated with the model as the first argument to this function. This means you can use any templates you like! We like to use [Hogan](http://twitter.github.io/hogan.js/).
4
Spelling and flow
4
.md
md
mit
ftlabs/fruitmachine
10062155
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062156
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062157
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062158
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062159
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062160
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062161
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062162
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062163
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062164
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062165
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062166
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062167
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062168
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062169
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update nuget packages to latest avalonia release. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.4.1-build2959-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.0" /> <!--<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />--> </ItemGroup>
1
update nuget packages to latest avalonia release.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10062170
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062171
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062172
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062173
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062174
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062175
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062176
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062177
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062178
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062179
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062180
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062181
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062182
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062183
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062184
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; int remaining = textPieceLength; while (true) { if (remaining > LENGTH_LIMIT) { // split in chunks of LENGTH_LIMIT _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); remaining -= LENGTH_LIMIT; } else { _elements.Add(new VisualLineText(this, remaining)); break; } } offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. /// </summary> public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace) { if (!HasStopsInVirtualSpace(mode)) allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> More fixes <DFF> @@ -165,7 +165,7 @@ namespace AvaloniaEdit.Rendering while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { - g.CachedInterest = (lineLength > LENGTH_LIMIT) ? -1: g.GetFirstInterestedOffset(offset + askInterestOffset); + g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", @@ -179,24 +179,9 @@ namespace AvaloniaEdit.Rendering if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; - int remaining = textPieceLength; - - while (true) - { - if (remaining > LENGTH_LIMIT) - { - // split in chunks of LENGTH_LIMIT - _elements.Add(new VisualLineText(this, LENGTH_LIMIT)); - remaining -= LENGTH_LIMIT; - } - else - { - _elements.Add(new VisualLineText(this, remaining)); - break; - } - } - - offset = textPieceEndOffset; + _elements.Add(new VisualLineText(this, textPieceLength)); + + offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop)
4
More fixes
19
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062185
<NME> zh-CN.js <BEF> ADDFILE <MSG> Merge pull request #276 from fakelbst/master i18n: add zh-CN locale <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales["zh-cn"] = { + grid: { + noDataContent: "暂无数据", + deleteConfirm: "确认删除?", + pagerFormat: "页码: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "上一页", + pageNextText: "下一页", + pageFirstText: "第一页", + pageLastText: "最后页", + loadMessage: "请稍后...", + invalidMessage: "数据有误!" + }, + + loadIndicator: { + message: "载入中..." + }, + + fields: { + control: { + searchModeButtonTooltip: "切换为搜索", + insertModeButtonTooltip: "切换为新增", + editButtonTooltip: "编辑", + deleteButtonTooltip: "删除", + searchButtonTooltip: "搜索", + clearFilterButtonTooltip: "清空过滤", + insertButtonTooltip: "插入", + updateButtonTooltip: "更新", + cancelEditButtonTooltip: "取消编辑" + } + }, + + validators: { + required: { message: "字段必填" }, + rangeLength: { message: "字段值长度超过定义范围" }, + minLength: { message: "字段长度过短" }, + maxLength: { message: "字段长度过长" }, + pattern: { message: "字段值不符合定义规则" }, + range: { message: "字段值超过定义范围" }, + min: { message: "字段值太小" }, + max: { message: "字段值太大" } + } + }; + +}(jsGrid, jQuery));
46
Merge pull request #276 from fakelbst/master
0
.js
js
mit
tabalinas/jsgrid
10062186
<NME> zh-CN.js <BEF> ADDFILE <MSG> Merge pull request #276 from fakelbst/master i18n: add zh-CN locale <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales["zh-cn"] = { + grid: { + noDataContent: "暂无数据", + deleteConfirm: "确认删除?", + pagerFormat: "页码: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "上一页", + pageNextText: "下一页", + pageFirstText: "第一页", + pageLastText: "最后页", + loadMessage: "请稍后...", + invalidMessage: "数据有误!" + }, + + loadIndicator: { + message: "载入中..." + }, + + fields: { + control: { + searchModeButtonTooltip: "切换为搜索", + insertModeButtonTooltip: "切换为新增", + editButtonTooltip: "编辑", + deleteButtonTooltip: "删除", + searchButtonTooltip: "搜索", + clearFilterButtonTooltip: "清空过滤", + insertButtonTooltip: "插入", + updateButtonTooltip: "更新", + cancelEditButtonTooltip: "取消编辑" + } + }, + + validators: { + required: { message: "字段必填" }, + rangeLength: { message: "字段值长度超过定义范围" }, + minLength: { message: "字段长度过短" }, + maxLength: { message: "字段长度过长" }, + pattern: { message: "字段值不符合定义规则" }, + range: { message: "字段值超过定义范围" }, + min: { message: "字段值太小" }, + max: { message: "字段值太大" } + } + }; + +}(jsGrid, jQuery));
46
Merge pull request #276 from fakelbst/master
0
.js
js
mit
tabalinas/jsgrid
10062187
<NME> de.js <BEF> ADDFILE <MSG> i18n: Add German locale <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.de = { + grid: { + noDataContent: "Die Daten konnten nicht gefunden werden", + deleteConfirm: "Möchten Sie die Daten unwiederruflich löschen?", + pagerFormat: "Seiten: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} von {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "Bitte warten...", + invalidMessage: "Ihre Eingabe ist nicht zulässig!" + }, + + loadIndicator: { + message: "Lädt..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Suche", + insertModeButtonTooltip: "Eintrag hinzufügen", + editButtonTooltip: "Bearbeiten", + deleteButtonTooltip: "Löschen", + searchButtonTooltip: "Eintrag finden", + clearFilterButtonTooltip: "Filter zurücksetzen", + insertButtonTooltip: "Hinzufügen", + updateButtonTooltip: "Speichern", + cancelEditButtonTooltip: "Abbrechen" + } + }, + + validators: { + required: { message: "Dies ist ein Pflichtfeld" }, + rangeLength: { message: "Die Länge der Eingabe liegt außerhalb des zulässigen Bereichs" }, + minLength: { message: "Die Eingabe ist zu kurz" }, + maxLength: { message: "Die Eingabe ist zu lang" }, + pattern: { message: "Die Eingabe entspricht nicht dem gewünschten Muster" }, + range: { message: "Der eingegebene Wert liegt außerhalb des zulässigen Bereichs" }, + min: { message: "Der eingegebene Wert ist zu niedrig" }, + max: { message: "Der eingegebene Wert ist zu hoch" } + } + }; + +}(jsGrid, jQuery));
46
i18n: Add German locale
0
.js
js
mit
tabalinas/jsgrid
10062188
<NME> de.js <BEF> ADDFILE <MSG> i18n: Add German locale <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.de = { + grid: { + noDataContent: "Die Daten konnten nicht gefunden werden", + deleteConfirm: "Möchten Sie die Daten unwiederruflich löschen?", + pagerFormat: "Seiten: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} von {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "Bitte warten...", + invalidMessage: "Ihre Eingabe ist nicht zulässig!" + }, + + loadIndicator: { + message: "Lädt..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Suche", + insertModeButtonTooltip: "Eintrag hinzufügen", + editButtonTooltip: "Bearbeiten", + deleteButtonTooltip: "Löschen", + searchButtonTooltip: "Eintrag finden", + clearFilterButtonTooltip: "Filter zurücksetzen", + insertButtonTooltip: "Hinzufügen", + updateButtonTooltip: "Speichern", + cancelEditButtonTooltip: "Abbrechen" + } + }, + + validators: { + required: { message: "Dies ist ein Pflichtfeld" }, + rangeLength: { message: "Die Länge der Eingabe liegt außerhalb des zulässigen Bereichs" }, + minLength: { message: "Die Eingabe ist zu kurz" }, + maxLength: { message: "Die Eingabe ist zu lang" }, + pattern: { message: "Die Eingabe entspricht nicht dem gewünschten Muster" }, + range: { message: "Der eingegebene Wert liegt außerhalb des zulässigen Bereichs" }, + min: { message: "Der eingegebene Wert ist zu niedrig" }, + max: { message: "Der eingegebene Wert ist zu hoch" } + } + }; + +}(jsGrid, jQuery));
46
i18n: Add German locale
0
.js
js
mit
tabalinas/jsgrid
10062189
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062190
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062191
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062192
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062193
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062194
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062195
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062196
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062197
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062198
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062199
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062200
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062201
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062202
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062203
<NME> CompletionWindowBase.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 System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix the wrong complete window position https://github.com/AvaloniaUI/AvaloniaEdit/issues/194 <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
fix the wrong complete window position
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062204
<NME> AccessTokenController.php <BEF> <?php namespace Dusterio\LumenPassport\Http\Controllers; use Laravel\Passport\Passport; use Laravel\Passport\Token; use Laminas\Diactoros\Response as Psr7Response; use Psr\Http\Message\ServerRequestInterface; use Dusterio\LumenPassport\LumenPassport; /** * Class AccessTokenController * @package Dusterio\LumenPassport\Http\Controllers */ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTokenController { /** * Authorize a client to access the user's account. * * @param ServerRequestInterface $request * @return Response */ public function issueToken(ServerRequestInterface $request) { $response = $this->withErrorHandling(function () use ($request) { $clientId = array_key_exists('client_id', (array) $request->getParsedBody()) ? ((array) $request->getParsedBody())['client_id'] : null; // Overwrite password grant at the last minute to add support for customized TTLs $this->server->enableGrantType( $this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId) ); return $this->server->respondToAccessTokenRequest($request, new Psr7Response); }); if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) { return $response; } $payload = json_decode($response->getBody()->__toString(), true); if (isset($payload['access_token'])) { /* @deprecated the jwt property will be removed in a future Laravel Passport release */ $token = $this->jwt->parse($payload['access_token']); if (method_exists($token, 'getClaim')) { $tokenId = $token->getClaim('jti'); } else if (method_exists($token, 'claims')) { $tokenId = $token->claims()->get('jti'); } else { throw new \RuntimeException('This package is not compatible with the Laravel Passport version used'); } $token = $this->tokens->find($tokenId); if (!$token instanceof Token) { return $response; } if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) { // We keep previous tokens for password clients } else { $this->revokeOrDeleteAccessTokens($token, $tokenId); } } return $response; } /** * Create and configure a Password grant instance. * * @return \League\OAuth2\Server\Grant\PasswordGrant */ private function makePasswordGrant() { $grant = new \League\OAuth2\Server\Grant\PasswordGrant( app()->make(\Laravel\Passport\Bridge\UserRepository::class), app()->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class) ); $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn()); return $grant; } /** * Revoke the user's other access tokens for the client. * * @param Token $token * @param string $tokenId * @return void */ protected function revokeOrDeleteAccessTokens(Token $token, $tokenId) { $query = Token::where('user_id', $token->user_id)->where('client_id', $token->client_id); if ($tokenId) { $query->where('id', '<>', $tokenId); } $query->update(['revoked' => true]); } } <MSG> r PHP5.6 support <DFF> @@ -23,8 +23,8 @@ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTok public function issueToken(ServerRequestInterface $request) { $response = $this->withErrorHandling(function () use ($request) { - $clientId = array_key_exists('client_id', (array) $request->getParsedBody()) - ? ((array) $request->getParsedBody())['client_id'] : null; + $input = (array) $request->getParsedBody(); + $clientId = isset($input['client_id']) ? $input['client_id'] : null; // Overwrite password grant at the last minute to add support for customized TTLs $this->server->enableGrantType(
2
r PHP5.6 support
2
.php
php
mit
dusterio/lumen-passport
10062205
<NME> layout-assembly.md <BEF> ## View Assembly When View modules are nested, a heiracical view structure is formed. For flexbibily, *FruitMachine* allows nested views to be assembled in a variety of ways. #### Manual ```js var layout = new Layout(); var apple = new Apple(); var orange = new Orange(); apple.add(orange); layout.add(apple); layout.children.length; //=> 1 apple.children.length; //=> 1 orange.children.length; //=> 0 ``` #### Lazy ```js var layout = new Layout({ children: { 1: { module: 'apple', children: { 1: { module: 'orange' } } } } }); layout.children.length; //=> 1 apple.children.length; //=> 1 orange.children.length; //=> 0 ``` #### Super lazy ```js var layout = fruitmachine({ module: 'layout', children: { 1: { module: 'apple', children: { 1: { module: 'orange' } } } } }); layout.children.length; //=> 1 apple.children.length; //=> 1 orange.children.length; //=> 0 ``` #### Removing modules Sometimes you may wish to add or replace modules before the layout is rendered. This is a good use case for `.remove()`. ```js var layout = fruitmachine({ module: 'layout', children: [ 1: { module: 'apple', children: { 1: { module: 'orange' } } } ] }); var apple = layout.module('apple'); var orange = layout.module('orange'); var banana = new Banana(); apple .remove(orange) .add(banana, { slot: 1 }); ``` <MSG> Merge branch 'master' of github.com:ftlabs/fruitmachine into dev <DFF> @@ -1,6 +1,6 @@ ## View Assembly -When View modules are nested, a heiracical view structure is formed. For flexbibily, *FruitMachine* allows nested views to be assembled in a variety of ways. +When View modules are nested, a heiracical view structure is formed. For flexibility, *FruitMachine* allows nested views to be assembled in a variety of ways. #### Manual
1
Merge branch 'master' of github.com:ftlabs/fruitmachine into dev
1
.md
md
mit
ftlabs/fruitmachine
10062206
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062207
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062208
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062209
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062210
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062211
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062212
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062213
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062214
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062215
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062216
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062217
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062218
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062219
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062220
<NME> TextFormatterFactory.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.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn Minor fixes <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
Merge pull request #25 from danwalmsley/minor-fixes-an-extensiosn
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062221
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062222
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062223
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062224
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062225
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062226
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062227
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062228
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062229
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062230
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062231
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062232
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062233
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062234
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062235
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge branch 'master' into fix-selection-issues <DFF> @@ -31,7 +31,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -49,7 +51,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -67,7 +71,9 @@ namespace AvaloniaEdit.Editing { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), - platform: new MockRuntimePlatform()))) + platform: new MockRuntimePlatform(), + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
9
Merge branch 'master' into fix-selection-issues
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062236
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062237
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062238
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062239
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062240
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062241
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062242
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062243
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062244
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062245
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062246
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062247
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062248
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062249
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit