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
10058550
<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. TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); } // 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). 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); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.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 arrange when document is changed. This fixes not rendering with single line of text. <DFF> @@ -254,6 +254,8 @@ namespace AvaloniaEdit.Editing 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).
2
invalidate arrange when document is changed.
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058551
<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. TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); } // 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). 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); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.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 arrange when document is changed. This fixes not rendering with single line of text. <DFF> @@ -254,6 +254,8 @@ namespace AvaloniaEdit.Editing 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).
2
invalidate arrange when document is changed.
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058552
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058553
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058554
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058555
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058556
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058557
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058558
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058559
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058560
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058561
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058562
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058563
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058564
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058565
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058566
<NME> SnippetReplaceableTextElement.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.Linq; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Snippets { /// <summary> /// Text element that is supposed to be replaced by the user. /// Will register an <see cref="IReplaceableActiveElement"/>. /// </summary> public class SnippetReplaceableTextElement : SnippetTextElement { /// <inheritdoc/> public override void Insert(InsertionContext context) { var start = context.InsertionPosition; base.Insert(context); var end = context.InsertionPosition; context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end)); } ///// <inheritdoc/> //public override Inline ToTextRun() //{ // return new Italic(base.ToTextRun()); //} } /// <summary> /// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>. /// </summary> public interface IReplaceableActiveElement : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; } internal sealed class ReplaceableActiveElement : IReplaceableActiveElement { private readonly InsertionContext _context; private readonly int _startOffset; private readonly int _endOffset; private TextAnchor _start; private TextAnchor _end; public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset) { _context = context; _startOffset = startOffset; _endOffset = endOffset; } private void AnchorDeleted(object sender, EventArgs e) { _context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted)); } public void OnInsertionCompleted() { // anchors must be created in OnInsertionCompleted because they should move only // due to user insertions, not due to insertions of other snippet parts _start = _context.Document.CreateAnchor(_startOffset); _start.MovementType = AnchorMovementType.BeforeInsertion; _end = _context.Document.CreateAnchor(_endOffset); _end.MovementType = AnchorMovementType.AfterInsertion; _start.Deleted += AnchorDeleted; _end.Deleted += AnchorDeleted; // Be careful with references from the document to the editing/snippet layer - use weak events // to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active. // The InsertionContext will keep us alive as long as the snippet is in interactive mode. TextDocumentWeakEventManager.TextChanged.AddHandler(_context.Document, OnDocumentTextChanged); _background = new Renderer { Layer = KnownLayer.Background, Element = this }; _foreground = new Renderer { Layer = KnownLayer.Text, Element = this }; _context.TextArea.TextView.BackgroundRenderers.Add(_background); _context.TextArea.TextView.BackgroundRenderers.Add(_foreground); _context.TextArea.Caret.PositionChanged += Caret_PositionChanged; Caret_PositionChanged(null, null); Text = GetText(); } public void Deactivate(SnippetEventArgs e) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(_context.Document, OnDocumentTextChanged); _context.TextArea.TextView.BackgroundRenderers.Remove(_background); _context.TextArea.TextView.BackgroundRenderers.Remove(_foreground); _context.TextArea.Caret.PositionChanged -= Caret_PositionChanged; } private bool _isCaretInside; private void Caret_PositionChanged(object sender, EventArgs e) { var s = Segment; if (s != null) { var newIsCaretInside = s.Contains(_context.TextArea.Caret.Offset, 0); if (newIsCaretInside != _isCaretInside) { _isCaretInside = newIsCaretInside; _context.TextArea.TextView.InvalidateLayer(_foreground.Layer); } } } private Renderer _background, _foreground; public string Text { get; private set; } private string GetText() { if (_start.IsDeleted || _end.IsDeleted) return string.Empty; return _context.Document.GetText(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } public event EventHandler TextChanged; void OnDocumentTextChanged(object sender, EventArgs e) { var newText = GetText(); if (Text != newText) { Text = newText; TextChanged?.Invoke(this, e); } } public bool IsEditable => true; public ISegment Segment { get { if (_start.IsDeleted || _end.IsDeleted) return null; return new SimpleSegment(_start.Offset, Math.Max(0, _end.Offset - _start.Offset)); } } private sealed class Renderer : IBackgroundRenderer { private static readonly IBrush BackgroundBrush = CreateBackgroundBrush(); private static readonly Pen ActiveBorderPen = CreateBorderPen(); private static IBrush CreateBackgroundBrush() { var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; return b; } private static Pen CreateBorderPen() { var p = new Pen(Brushes.Black, dashStyle: DashStyle.Dot); return p; } internal ReplaceableActiveElement Element; public KnownLayer Layer { get; set; } public void Draw(TextView textView, DrawingContext drawingContext) { var s = Element.Segment; if (s != null) { var geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, BorderThickness = ActiveBorderPen?.Thickness ?? 0 }; if (Layer == KnownLayer.Background) { geoBuilder.AddSegment(textView, s); drawingContext.DrawGeometry(BackgroundBrush, null, geoBuilder.CreateGeometry()); } else { // draw foreground only if active if (Element._isCaretInside) { geoBuilder.AddSegment(textView, s); foreach (var boundElement in Element._context.ActiveElements.OfType<BoundActiveElement>()) { if (boundElement.TargetElement == Element) { geoBuilder.AddSegment(textView, boundElement.Segment); geoBuilder.CloseFigure(); } } drawingContext.DrawGeometry(null, ActiveBorderPen, geoBuilder.CreateGeometry()); } } } } } } } <MSG> Merge pull request #59 from jeffreye/support-multithreading Multithreading <DFF> @@ -19,6 +19,7 @@ using System; using System.Linq; using Avalonia.Media; +using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -174,7 +175,7 @@ namespace AvaloniaEdit.Snippets private static IBrush CreateBackgroundBrush() { - var b = new SolidColorBrush(Colors.LimeGreen) { Opacity = 0.4 }; + var b = new ImmutableSolidColorBrush(Colors.LimeGreen, 0.4); return b; }
2
Merge pull request #59 from jeffreye/support-multithreading
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058567
<NME> LumenPassport.php <BEF> <?php namespace Dusterio\LumenPassport; use Illuminate\Support\Arr; use Laravel\Passport\Passport; use DateTimeInterface; use Carbon\Carbon; use Laravel\Lumen\Application; use Laravel\Lumen\Routing\Router; class LumenPassport { /** * Allow simultaneous logins for users * * @var bool */ public static $allowMultipleTokens = false; /** * The date when access tokens expire (specific per password client). * * @var array */ public static $tokensExpireAt = []; /** * Instruct Passport to keep revoked tokens pruned. */ public static function allowMultipleTokens() { static::$allowMultipleTokens = true; } /** * Get or set when access tokens expire. * * @param \DateTimeInterface|null $date * @param int $clientId * @return \DateInterval|static */ public static function tokensExpireIn(DateTimeInterface $date = null, $clientId = null) { if (! $clientId) return Passport::tokensExpireIn($date); if (is_null($date)) { return isset(static::$tokensExpireAt[$clientId]) ? Carbon::now()->diff(static::$tokensExpireAt[$clientId]) : Passport::tokensExpireIn(); } else { static::$tokensExpireAt[$clientId] = $date; } return new static; } /** * Get a Passport route registrar. * * @param callable|Router|Application $callback * @param array $options * @return RouteRegistrar */ public static function routes($callback = null, array $options = []) { if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)/', $callback->version())) $callback = $callback->router; $callback = $callback ?: function ($router) { $router->all(); }; $defaultOptions = [ 'prefix' => 'oauth', 'namespace' => '\Laravel\Passport\Http\Controllers', ]; $options = array_merge($defaultOptions, $options); $callback->group(Arr::except($options, ['namespace']), function ($router) use ($callback, $options) { $routes = new RouteRegistrar($router, $options); $routes->all(); }); } } <MSG> Update LumenPassport.php Lumen 9.* <DFF> @@ -64,7 +64,7 @@ class LumenPassport */ public static function routes($callback = null, array $options = []) { - if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)/', $callback->version())) $callback = $callback->router; + if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)|(9\..*)/', $callback->version())) $callback = $callback->router; $callback = $callback ?: function ($router) { $router->all();
1
Update LumenPassport.php
1
.php
php
mit
dusterio/lumen-passport
10058568
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058569
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058570
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058571
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058572
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058573
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058574
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058575
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058576
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058577
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058578
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058579
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058580
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058581
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058582
<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> /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, new TextDocument()); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } 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 AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> 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() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// 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> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// 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) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </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; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { 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> 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> add constructor so its possible to not waste time and memory allocating a empty textdocument. <DFF> @@ -67,14 +67,19 @@ namespace AvaloniaEdit /// <summary> /// Creates a new TextEditor instance. /// </summary> - protected TextEditor(TextArea textArea) + protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) + { + + } + + protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); - SetValue(DocumentProperty, new TextDocument()); + SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; }
7
add constructor so its possible to not waste time and memory allocating a
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058583
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058584
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058585
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058586
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058587
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058588
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058589
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058590
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058591
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058592
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058593
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058594
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058595
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058596
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058597
<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.5.1-build3388-alpha" /> </ItemGroup> </Project> </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 avalonia with gtk3 fixes. <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.5.1-build3388-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3397-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia with gtk3 fixes.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058598
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058599
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058600
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058601
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058602
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058603
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058604
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058605
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058606
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058607
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058608
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058609
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058610
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058611
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058612
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.1</TargetFramework> </PropertyGroup> <ItemGroup> <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)" /> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </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> netstandard1.3 to support new avalonia. <DFF> @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard1.1</TargetFramework> + <TargetFramework>netstandard1.3</TargetFramework> </PropertyGroup> <ItemGroup> @@ -37,7 +37,7 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3552-alpha" /> </ItemGroup> </Project> \ No newline at end of file
2
netstandard1.3 to support new avalonia.
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10058613
<NME> define.js <BEF> /*jslint browser:true, node:true, laxbreak:true*/ 'use strict'; module.exports = function(fm) { /** * Defines a module. * * Options: * * - `name {String}` the name of the module * - `tag {String}` the tagName to use for the root element * - `classes {Array}` a list of classes to add to the root element * - `template {Function}` the template function to use when rendering * - `helpers {Array}` a list of helpers to apply to the module * - `initialize {Function}` custom logic to run when module instance created * - `setup {Function}` custom logic to run when `.setup()` is called (directly or indirectly) * - `teardown {Function}` custom logic to unbind/undo anything setup introduced (called on `.destroy()` and sometimes on `.setup()` to avoid double binding events) * - `destroy {Function}` logic to permanently destroy all references * * @param {Object|View} props * @return {View} * @public true */ return function(props) { var Module = ('object' === typeof props) ? fm.Module.extend(props) : props; // Allow modules to be named // via 'name:' or 'module:' var proto = Module.prototype; var name = proto.name || proto._module; // Store the module by module type // so that module can be referred to // by just a string in layout definitions if (name) fm.modules[name] = Module; return Module; }; }; */ function protect(keys, ob) { for (var key in ob) { if (~keys.indexOf(key)) { ob['_' + key] = ob[key]; delete ob[key]; } <MSG> Fix bug whereby protect was prefixing the prototype methods as well as static <DFF> @@ -63,7 +63,7 @@ module.exports = function(props) { */ function protect(keys, ob) { for (var key in ob) { - if (~keys.indexOf(key)) { + if (ob.hasOwnProperty(key) && ~keys.indexOf(key)) { ob['_' + key] = ob[key]; delete ob[key]; }
1
Fix bug whereby protect was prefixing the prototype methods as well as static
1
.js
js
mit
ftlabs/fruitmachine
10058614
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058615
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058616
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058617
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058618
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058619
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058620
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058621
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058622
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058623
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058624
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058625
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058626
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058627
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058628
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. /// </summary> public string SearchPattern { get => GetValue(SearchPatternProperty); set => SetValue(SearchPatternProperty, value); } public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); /// <summary> /// Checks if replacemode is allowed /// </summary> /// <returns>False if editor is not null and readonly</returns> private static bool ValidateReplaceMode(SearchPanel panel, bool v1) { if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() { Close(); _textArea.DocumentChanged -= TextArea_DocumentChanged; if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler); } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { FindPrevious(); } else { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained _renderer.CurrentResults.Clear(); _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour. <DFF> @@ -437,7 +437,12 @@ namespace AvaloniaEdit.Search { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); - _textArea.Caret.BringCaretToView(_border.Bounds.Height + _textArea.TextView.DefaultLineHeight); + + double distanceToViewBorder = _border == null ? + Caret.MinimumDistanceToViewBorder : + _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; + _textArea.Caret.BringCaretToView(distanceToViewBorder); + // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); }
6
Fix null reference exception on SearchPanel.SelectResult method when _border is not yet initialized. In that case, we use the minimum distance to view border. It is the default behaviour.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058629
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058630
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058631
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058632
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058633
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058634
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058635
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058636
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058637
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058638
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058639
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058640
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058641
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058642
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058643
<NME> HtmlClipboardTests.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.Windows; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Highlighting { [TestFixture] public class HtmlClipboardTests { TextDocument document; DocumentHighlighter highlighter; public HtmlClipboardTests() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } [Test, Ignore("")] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">using</span> System.Text;<br>" + Environment.NewLine + "&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #ff0000; \">string</span> " + "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } [Test, Ignore("")] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 }; string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); Assert.AreEqual("<span style=\"color: #008000; font-weight: bold; \">sin</span>", html); } } } <MSG> Make nunit tests to pass Complete interface implementations, fix errors, uncomment tests, etc ... <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Highlighting highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); } - [Test, Ignore("")] + [Test] public void FullDocumentTest() { var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Highlighting "text = <span style=\"color: #191970; font-weight: bold; \">SomeMethod</span>();", html); } - [Test, Ignore("")] + [Test] public void PartOfHighlightedWordTest() { var segment = new TextSegment { StartOffset = 1, Length = 3 };
2
Make nunit tests to pass
2
.cs
Tests/Highlighting/HtmlClipboardTests
mit
AvaloniaUI/AvaloniaEdit
10058644
<NME> introduction.md <BEF> ADDFILE <MSG> Updated readme <DFF> @@ -0,0 +1,29 @@ +## 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 refering to a module we mean a small 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 bring along your own types of Model should you wish. If you wish to go down this route, you just need to tell FruitMachine how it can get hold of the Model's data when it need to 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! Although we like to use [Hogan](http://twitter.github.io/hogan.js/). \ No newline at end of file
29
Updated readme
0
.md
md
mit
ftlabs/fruitmachine
10058645
<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> } set { Debug.WriteLine($"Setting OffsetY: {value.Y}"); //Dispatcher.UIThread.InvokeAsync(() => { TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); }//); SetAndRaise(OffsetProperty, ref _offset, value); } } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } 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> remove debug code. <DFF> @@ -1063,14 +1063,8 @@ namespace AvaloniaEdit.Editing } set { + TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - - Debug.WriteLine($"Setting OffsetY: {value.Y}"); - //Dispatcher.UIThread.InvokeAsync(() => - { - TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - }//); - SetAndRaise(OffsetProperty, ref _offset, value); } }
1
remove debug code.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058646
<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> } set { Debug.WriteLine($"Setting OffsetY: {value.Y}"); //Dispatcher.UIThread.InvokeAsync(() => { TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); }//); SetAndRaise(OffsetProperty, ref _offset, value); } } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } 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> remove debug code. <DFF> @@ -1063,14 +1063,8 @@ namespace AvaloniaEdit.Editing } set { + TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - - Debug.WriteLine($"Setting OffsetY: {value.Y}"); - //Dispatcher.UIThread.InvokeAsync(() => - { - TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - }//); - SetAndRaise(OffsetProperty, ref _offset, value); } }
1
remove debug code.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058647
<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> } set { Debug.WriteLine($"Setting OffsetY: {value.Y}"); //Dispatcher.UIThread.InvokeAsync(() => { TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); }//); SetAndRaise(OffsetProperty, ref _offset, value); } } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } 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> remove debug code. <DFF> @@ -1063,14 +1063,8 @@ namespace AvaloniaEdit.Editing } set { + TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - - Debug.WriteLine($"Setting OffsetY: {value.Y}"); - //Dispatcher.UIThread.InvokeAsync(() => - { - TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - }//); - SetAndRaise(OffsetProperty, ref _offset, value); } }
1
remove debug code.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058648
<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> } set { Debug.WriteLine($"Setting OffsetY: {value.Y}"); //Dispatcher.UIThread.InvokeAsync(() => { TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); }//); SetAndRaise(OffsetProperty, ref _offset, value); } } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } 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> remove debug code. <DFF> @@ -1063,14 +1063,8 @@ namespace AvaloniaEdit.Editing } set { + TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - - Debug.WriteLine($"Setting OffsetY: {value.Y}"); - //Dispatcher.UIThread.InvokeAsync(() => - { - TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - }//); - SetAndRaise(OffsetProperty, ref _offset, value); } }
1
remove debug code.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10058649
<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> } set { Debug.WriteLine($"Setting OffsetY: {value.Y}"); //Dispatcher.UIThread.InvokeAsync(() => { TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); }//); SetAndRaise(OffsetProperty, ref _offset, value); } } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } 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> remove debug code. <DFF> @@ -1063,14 +1063,8 @@ namespace AvaloniaEdit.Editing } set { + TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - - Debug.WriteLine($"Setting OffsetY: {value.Y}"); - //Dispatcher.UIThread.InvokeAsync(() => - { - TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); - }//); - SetAndRaise(OffsetProperty, ref _offset, value); } }
1
remove debug code.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit