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
|
---|---|---|---|---|---|---|---|---|
10064750 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064751 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064752 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064753 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064754 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064755 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064756 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064757 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064758 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064759 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064760 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064761 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
}
#endregion
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void 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> prepare for upcoming scenegraph upgrade in avalonia
bind background of text area (required or mouse clicks wont be caught)
dont render if visual lines are not valid.
<DFF> @@ -75,6 +75,8 @@ namespace AvaloniaEdit
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, new TextDocument());
+
+ textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
| 2 | prepare for upcoming scenegraph upgrade in avalonia | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064762 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064763 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064764 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064765 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064766 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064767 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064768 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064769 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064770 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064771 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064772 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064773 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064774 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064775 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064776 | <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;
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
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);
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();
}
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>
base.OnPointerPressed(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
{
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> Merge pull request #87 from HendrikMennen/FixSearch
Fix searchpanel crash
<DFF> @@ -282,7 +282,7 @@ namespace AvaloniaEdit.Search
base.OnTemplateApplied(e);
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
- _messageViewContent = _messageView.FindControl<ContentPresenter>("PART_MessageContent");
+ _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
@@ -511,6 +511,12 @@ namespace AvaloniaEdit.Search
base.OnPointerPressed(e);
}
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ Cursor = Cursor.Default;
+ base.OnPointerMoved(e);
+ }
+
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
| 7 | Merge pull request #87 from HendrikMennen/FixSearch | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064777 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064778 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064779 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064780 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064781 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064782 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064783 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064784 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064785 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064786 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064787 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064788 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064789 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064790 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064791 | <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();
});
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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> ensure the scrollbar is synchronised with the caret position.
<DFF> @@ -616,6 +616,11 @@ namespace AvaloniaEdit.Editing
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line);
+
+ Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ (this as ILogicalScrollable).InvalidateScroll?.Invoke();
+ });
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
| 5 | ensure the scrollbar is synchronised with the caret position. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064792 | <NME> AccessTokenController.php
<BEF> <?php
namespace Dusterio\LumenPassport\Http\Controllers;
use Laravel\Passport\Passport;
use Laravel\Passport\Token;
use Laminas\Diactoros\Response as Psr7Response;
use Psr\Http\Message\ServerRequestInterface;
use Dusterio\LumenPassport\LumenPassport;
/**
* Class AccessTokenController
* @package Dusterio\LumenPassport\Http\Controllers
*/
class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTokenController
{
/**
* Authorize a client to access the user's account.
*
* @param ServerRequestInterface $request
* @return Response
*/
public function issueToken(ServerRequestInterface $request)
{
$response = $this->withErrorHandling(function () use ($request) {
$input = (array) $request->getParsedBody();
$clientId = isset($input['client_id']) ? $input['client_id'] : null;
// Overwrite password grant at the last minute to add support for customized TTLs
$this->server->enableGrantType(
$this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId)
);
return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
});
$tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
$token = $this->tokens->find($tokenId);
if (! $token->client->firstParty() || ! LumenPassport::$allowMultipleTokens) {
// We keep previous tokens for password clients
} else {
$this->revokeOrDeleteAccessTokens($token, $tokenId);
if (isset($payload['access_token'])) {
/* @deprecated the jwt property will be removed in a future Laravel Passport release */
$token = $this->jwt->parse($payload['access_token']);
if (method_exists($token, 'getClaim')) {
$tokenId = $token->getClaim('jti');
} else if (method_exists($token, 'claims')) {
$tokenId = $token->claims()->get('jti');
} else {
throw new \RuntimeException('This package is not compatible with the Laravel Passport version used');
}
$token = $this->tokens->find($tokenId);
if (!$token instanceof Token) {
return $response;
}
$token->client_id, $token->user_id, $tokenId, Passport::$pruneRevokedTokens
);
}
}
}
}
return $response;
}
/**
* Create and configure a Password grant instance.
*
* @return \League\OAuth2\Server\Grant\PasswordGrant
*/
private function makePasswordGrant()
{
$grant = new \League\OAuth2\Server\Grant\PasswordGrant(
app()->make(\Laravel\Passport\Bridge\UserRepository::class),
app()->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}
/**
* Revoke the user's other access tokens for the client.
*
* @param Token $token
* @param string $tokenId
* @return void
*/
protected function revokeOrDeleteAccessTokens(Token $token, $tokenId)
{
$query = Token::where('user_id', $token->user_id)->where('client_id', $token->client_id);
if ($tokenId) {
$query->where('id', '<>', $tokenId);
}
$query->update(['revoked' => true]);
}
}
<MSG> r Fixed typo
<DFF> @@ -36,7 +36,7 @@ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTok
$tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
$token = $this->tokens->find($tokenId);
- if (! $token->client->firstParty() || ! LumenPassport::$allowMultipleTokens) {
+ if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
// We keep previous tokens for password clients
} else {
$this->revokeOrDeleteAccessTokens($token, $tokenId);
@@ -59,4 +59,4 @@ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTok
$token->client_id, $token->user_id, $tokenId, Passport::$pruneRevokedTokens
);
}
-}
\ No newline at end of file
+}
| 2 | r Fixed typo | 2 | .php | php | mit | dusterio/lumen-passport |
10064793 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064794 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064795 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064796 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064797 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064798 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064799 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064800 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064801 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064802 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064803 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064804 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064805 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064806 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064807 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
{
_toolTipContent.Content = description;
}
_toolTip.IsOpen = false; //Popup needs to be closed to change position
//Calculate offset for tooltip
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y;
int yoffset = index - scrollIndex;
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> Fix pressing enter when list is empty
<DFF> @@ -122,8 +122,6 @@ namespace AvaloniaEdit.CodeCompletion
if (yoffset < 0) yoffset = 0;
if ((yoffset+1) * 20 > MaxHeight) yoffset--;
_toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height
-
- Console.WriteLine(CompletionList.ListBox.ScrollViewer.Offset.Y + " " + index);
}
_toolTip.IsOpen = true;
}
| 0 | Fix pressing enter when list is empty | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064808 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064809 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064810 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064811 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064812 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064813 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064814 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064815 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064816 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064817 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064818 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064819 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064820 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064821 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064822 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ShowTabs = true;
//_textEditor.Options.ShowSpaces = true;
//_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Add button to view tabs/spaces/EOL
Uniform button height and alignment in the header panel.
<DFF> @@ -16,7 +16,7 @@ using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
-
+using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
@@ -39,6 +39,7 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
@@ -57,9 +58,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
- _textEditor.Options.ShowTabs = true;
- //_textEditor.Options.ShowSpaces = true;
- //_textEditor.Options.ShowEndOfLine = true;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
| 2 | Add button to view tabs/spaces/EOL | 4 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064823 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064824 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064825 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064826 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064827 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064828 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064829 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064830 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064831 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064832 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064833 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064834 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064835 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064836 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064837 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<Version>0.10.9</Version>
</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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<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> Update to Avalonia 0.10.0
<DFF> @@ -2,8 +2,8 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <WarningsNotAsErrors>612,618</WarningsNotAsErrors>
- <Version>0.10.9</Version>
+ <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
+ <Version>0.10.10</Version>
</PropertyGroup>
<ItemGroup>
| 2 | Update to Avalonia 0.10.0 | 2 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10064838 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var view = require('./view');
var define = require('./define');
var utils = require('utils');
/**
* Express-style function for
* Options:
*
* - `Model` A model constructor to use (must have `.toJSON()`)
*
* @param {Object} options
*/
module.exports = function(options) {
/**
* Shortcut method for
* creating lazy views.
*
* @param {Object} options
* @return {Module}
*/
function fm(options) {
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
}
fm.create = module.exports;
fm.Model = options.Model;
templateInstance: 'child'
};
return fm;
};
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
<MSG> Add inflation events
<DFF> @@ -22,6 +22,7 @@
var view = require('./view');
var define = require('./define');
var utils = require('utils');
+var events = require('event');
/**
* Express-style function for
@@ -53,5 +54,5 @@ module.exports = function(options) {
templateInstance: 'child'
};
- return fm;
+ return events(fm);
};
\ No newline at end of file
| 2 | Add inflation events | 1 | .js | js | mit | ftlabs/fruitmachine |
10064839 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064840 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064841 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064842 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064843 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064844 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064845 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064846 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064847 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064848 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064849 | <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;
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
DispatcherPriority.Background);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
{
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
DispatcherPriority.Background);
}
}
else
{
TextView.Redraw(oldSegment, DispatcherPriority.Background);
TextView.Redraw(newSegment, DispatcherPriority.Background);
}
}
_selection = value;
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> Fix occasional selection stutter #126
https://github.com/icsharpcode/AvalonEdit/pull/126
<DFF> @@ -442,7 +442,7 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
@@ -450,13 +450,13 @@ namespace AvaloniaEdit.Editing
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
- DispatcherPriority.Background);
+ DispatcherPriority.Render);
}
}
else
{
- TextView.Redraw(oldSegment, DispatcherPriority.Background);
- TextView.Redraw(newSegment, DispatcherPriority.Background);
+ TextView.Redraw(oldSegment, DispatcherPriority.Render);
+ TextView.Redraw(newSegment, DispatcherPriority.Render);
}
}
_selection = value;
| 4 | Fix occasional selection stutter #126 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.