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
10057450
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057451
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057452
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057453
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057454
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057455
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057456
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057457
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057458
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057459
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057460
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057461
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057462
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057463
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057464
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057465
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Adjust version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.999-cibuild0022712-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.41</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.999-cibuild0022712-beta</Version> </PropertyGroup> </Project>
1
Adjust version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057466
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057467
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057468
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057469
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057470
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057471
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057472
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057473
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057474
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057475
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057476
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057477
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057478
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057479
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057480
<NME> GenericLineTransformer.cs <BEF> using Avalonia.Media; using Avalonia.Media.Immutable; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.TextMate { public abstract class GenericLineTransformer : DocumentColorizingTransformer { private Action<Exception> _exceptionHandler; protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) public void SetTextStyle( length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) { e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); } }); } } public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) { if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) { length = (line.EndOffset - startIndex) - line.Offset - startIndex; } int startOffset = line.Offset + startIndex; int endoffset = line.Offset + startIndex + length; if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) { ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } else { ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); } } } } if (background != null) visualLine.TextRunProperties.SetBackgroundBrush(background); if (isUnderline) { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } if (visualLine.TextRunProperties.Typeface.Style != fontStyle || visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { visualLine.TextRunProperties.SetTypeface(new Typeface( visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth)); } } } } <MSG> Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline <DFF> @@ -1,6 +1,4 @@ using Avalonia.Media; -using Avalonia.Media.Immutable; - using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; @@ -15,8 +13,19 @@ namespace AvaloniaEdit.TextMate protected abstract void TransformLine(DocumentLine line, ITextRunConstructionContext context); - public void SetTextOpacity(DocumentLine line, int startIndex, int length, double opacity) + public void SetTextStyle( + DocumentLine line, + int startIndex, + int length, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { + int startOffset = 0; + int endOffset = 0; + if (startIndex >= 0 && length > 0) { if ((line.Offset + startIndex + length) > line.EndOffset) @@ -24,53 +33,48 @@ namespace AvaloniaEdit.TextMate length = (line.EndOffset - startIndex) - line.Offset - startIndex; } - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; - - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); - } + startOffset = line.Offset + startIndex; + endOffset = line.Offset + startIndex + length; } else { - ChangeLinePart(line.Offset, line.EndOffset, e => - { - if (e.TextRunProperties.ForegroundBrush is ISolidColorBrush solidBrush) - { - e.TextRunProperties.ForegroundBrush = new ImmutableSolidColorBrush(solidBrush.Color, opacity); - } - }); + startOffset = line.Offset; + endOffset = line.EndOffset; } + + if (startOffset > CurrentContext.Document.TextLength || + endOffset > CurrentContext.Document.TextLength) + return; + + ChangeLinePart( + startOffset, + endOffset, + visualLine => ChangeVisualLine(visualLine, foreground, background, fontStyle, fontWeigth, isUnderline)); } - public void SetTextStyle(DocumentLine line, int startIndex, int length, IBrush foreground) + void ChangeVisualLine( + VisualLineElement visualLine, + IBrush foreground, + IBrush background, + FontStyle fontStyle, + FontWeight fontWeigth, + bool isUnderline) { - if (startIndex >= 0 && length > 0) - { - if ((line.Offset + startIndex + length) > line.EndOffset) - { - length = (line.EndOffset - startIndex) - line.Offset - startIndex; - } + if (foreground != null) + visualLine.TextRunProperties.ForegroundBrush = foreground; - int startOffset = line.Offset + startIndex; - int endoffset = line.Offset + startIndex + length; + if (background != null) + visualLine.TextRunProperties.BackgroundBrush = background; - if (startOffset < CurrentContext.Document.TextLength && endoffset < CurrentContext.Document.TextLength) - { - ChangeLinePart(startOffset, endoffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); - } - } - else + visualLine.TextRunProperties.Underline = isUnderline; + + if (visualLine.TextRunProperties.Typeface.Style != fontStyle || + visualLine.TextRunProperties.Typeface.Weight != fontWeigth) { - ChangeLinePart(line.Offset, line.EndOffset, e => { e.TextRunProperties.ForegroundBrush = foreground; }); + visualLine.TextRunProperties.Typeface = new Typeface( + visualLine.TextRunProperties.Typeface.FontFamily, fontStyle, fontWeigth); } + } } } \ No newline at end of file
43
Extended the GenericLineTransformer to accept background, fontStyle, fontWeigth and isUnderline
39
.cs
TextMate/GenericLineTransformer
mit
AvaloniaUI/AvaloniaEdit
10057481
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057482
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057483
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057484
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057485
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057486
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057487
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057488
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057489
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057490
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057491
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057492
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057493
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057494
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057495
<NME> XshdColor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Media; namespace AvaloniaEdit.Highlighting.Xshd { /// <summary> /// A color in an Xshd file. /// </summary> public class XshdColor : XshdElement { /// <summary> /// Gets/sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the foreground brush. /// </summary> public HighlightingBrush Foreground { get; set; } /// <summary> /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } /// <summary> /// Gets/sets the font weight. /// </summary> public FontWeight? FontWeight { get; set; } /// <summary> /// Gets/sets the underline flag /// </summary> public bool? Underline { get; set; } /// <summary> /// Gets/sets the strikethrough flag /// </summary> public bool? Strikethrough { get; set; } /// <summary> /// Gets/sets the font style. /// </summary> public FontStyle? FontStyle { get; set; } /// <summary> /// Gets/Sets the example text that demonstrates where the color is used. /// </summary> public string ExampleText { get; set; } ///// <summary> ///// Serializes this XshdColor instance. ///// </summary> //public virtual void GetObjectData(SerializationInfo info, StreamingContext context) //{ // if (info == null) // throw new ArgumentNullException("info"); // info.AddValue("Name", this.Name); // info.AddValue("Foreground", this.Foreground); // info.AddValue("Background", this.Background); // info.AddValue("HasUnderline", this.Underline.HasValue); // if (this.Underline.HasValue) // info.AddValue("Underline", this.Underline.Value); // info.AddValue("HasWeight", this.FontWeight.HasValue); // if (this.FontWeight.HasValue) // info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight()); // info.AddValue("HasStyle", this.FontStyle.HasValue); // if (this.FontStyle.HasValue) // info.AddValue("Style", this.FontStyle.Value.ToString()); // info.AddValue("ExampleText", this.ExampleText); //} /// <inheritdoc/> public override object AcceptVisitor(IXshdVisitor visitor) { return visitor.VisitColor(this); } } } <MSG> Merge pull request #115 from alxnull/feat/md-fontsize Port of font family & font size highlighting support from AvalonEdit <DFF> @@ -39,7 +39,17 @@ namespace AvaloniaEdit.Highlighting.Xshd /// Gets/sets the background brush. /// </summary> public HighlightingBrush Background { get; set; } - + + /// <summary> + /// Gets/sets the font family + /// </summary> + public FontFamily FontFamily { get; set; } + + /// <summary> + /// Gets/sets the font size. + /// </summary> + public int? FontSize { get; set; } + /// <summary> /// Gets/sets the font weight. /// </summary>
11
Merge pull request #115 from alxnull/feat/md-fontsize
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057496
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057497
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057498
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057499
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057500
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057501
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057502
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057503
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057504
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057505
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057506
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057507
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057508
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057509
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057510
<NME> log.tmLanguage.json <BEF> ADDFILE <MSG> Add missing log grammar files <DFF> @@ -0,0 +1,125 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/emilast/vscode-logfile-highlighter/commit/19807c6a80d29b03ad69e02ffe39e5869a9ce107", + "name": "Log file", + "scopeName": "text.log", + "patterns": [ + { + "match": "\\b(Trace)\\b:", + "name": "comment log.verbose" + }, + { + "match": "(?i)\\[(verbose|verb|vrb|vb|v)\\]", + "name": "comment log.verbose" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bV\\b", + "name": "comment log.verbose" + }, + { + "match": "\\b(DEBUG|Debug)\\b|(?i)\\b(debug)\\:", + "name": "markup.changed log.debug" + }, + { + "match": "(?i)\\[(debug|dbug|dbg|de|d)\\]", + "name": "markup.changed log.debug" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bD\\b", + "name": "markup.changed log.debug" + }, + { + "match": "\\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\\b|(?i)\\b(info|information)\\:", + "name": "markup.inserted log.info" + }, + { + "match": "(?i)\\[(information|info|inf|in|i)\\]", + "name": "markup.inserted log.info" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bI\\b", + "name": "markup.inserted log.info" + }, + { + "match": "\\b(WARNING|WARN|Warn|WW)\\b|(?i)\\b(warning)\\:", + "name": "markup.deleted log.warning" + }, + { + "match": "(?i)\\[(warning|warn|wrn|wn|w)\\]", + "name": "markup.deleted log.warning" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bW\\b", + "name": "markup.deleted log.warning" + }, + { + "match": "\\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\\b|(?i)\\b(error)\\:", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?i)\\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)\\]", + "name": "string.regexp, strong log.error" + }, + { + "match": "(?<=^|[\\s\\d\\p]*)\\bE\\b", + "name": "string.regexp, strong log.error" + }, + { + "match": "\\b\\d{4}-\\d{2}-\\d{2}(T|\\b)", + "name": "comment log.date" + }, + { + "match": "(?<=|(^|\\s))\\d{2}[^\\w\\s]\\d{2}[^\\w\\s]\\d{4}\\b", + "name": "comment log.date" + }, + { + "match": "\\d{1,2}:\\d{2}(:\\d{2}([.,]\\d{1,})?)?(Z| ?[+-]\\d{1,2}:\\d{2})?\\b", + "name": "comment log.date" + }, + { + "match": "\\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\\b", + "name": "constant.language" + }, + { + "match": "\\b[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9a-fA-F]{2,}[:-])+[0-9a-fA-F]{2,}+\\b", + "name": "constant.language log.constant" + }, + { + "match": "\\b([0-9]+|true|false|null)\\b", + "name": "constant.language log.constant" + }, + { + "match": "\"[^\"]*\"", + "name": "string log.string" + }, + { + "match": "(?<![\\w])'[^']*'", + "name": "string log.string" + }, + { + "match": "\\b([a-zA-Z.]*Exception)\\b", + "name": "string.regexp, emphasis log.exceptiontype" + }, + { + "begin": "^[\\t ]*at", + "end": "$", + "name": "string.key, emphasis log.exception" + }, + { + "match": "\\b[a-z]+://\\S+\\b/?", + "name": "constant.language log.constant" + }, + { + "match": "(?<![\\w/\\\\])([\\w-]+\\.)+([\\w-])+(?![\\w/\\\\])", + "name": "constant.language log.constant" + } + ] +} \ No newline at end of file
125
Add missing log grammar files
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10057511
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057512
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057513
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057514
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057515
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057516
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057517
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057518
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057519
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057520
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057521
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057522
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057523
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057524
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057525
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Added failing tests <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Added failing tests
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10057526
<NME> module-helpers.md <BEF> ## Helpers Helpers are small reusable plug-ins that you can write to add extra features to a View module ([working example](http://ftlabs.github.io/fruitmachine/examples/helpers)). ### Defining helpers A helper is simply a function accepting the View module instance as the first argument. The helper can listen to events on the View module and bolt functionality onto the view. Helpers should clear up after themselves. For example if they create variables or bind to events on `setup`, they should be unset and unbound on `teardown`. ```js var myHelper = function(module) { // Add functionality module.on('before setup', function() { /* 1 */ module.sayName = function() { return 'My name is ' + module.name; }; }); // Tidy up module.on('teardown', function() { delete module.sayName; }); }; ``` 1. *It is often useful to hook into the `before setup` event so that added functionality is available inside the module's `setup` function.* ### Attaching helpers At definition: ```js var Apple = fruitmachine.define({ name: 'apple', helpers: [ myHelper ] }); ``` ...or instantiation: ```js var apple = new Apple({ helpers: [ myHelper ] }); ``` ### Using features ```js apple.sayName(); //=> 'My name is apple' ``` ### Community Helpers ("Plugins") Helpers can be released as plugins, if you would like to submit your helper to this list [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules. <MSG> Add some more helpers <DFF> @@ -58,3 +58,5 @@ apple.sayName(); Helpers can be released as plugins, if you would like to submit your helper to this list [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules. +- [fruitmachine-bindall](https://github.com/ftlabs/fruitmachine-bindall)] automatically binds all the methods in a module to instances of that module. +- [fruitmachine-media(https://github.com/ftlabs/fruitmachine-media)] allows you to create resposnive components. Set up media queries for different states and this plugin will allow you to hook into per state setup and teardown events when those media queries match.
2
Add some more helpers
0
.md
md
mit
ftlabs/fruitmachine
10057527
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057528
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057529
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057530
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057531
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057532
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057533
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057534
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057535
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057536
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057537
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057538
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057539
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057540
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057541
<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 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; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Text; using Avalonia.Layout; namespace AvaloniaEdit.Editing { 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; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); 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> Merge pull request #39 from danwalmsley/update-avalonia Update avalonia <DFF> @@ -16,19 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; using Avalonia; -using AvaloniaEdit.Document; -using AvaloniaEdit.Indentation; -using AvaloniaEdit.Rendering; -using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -36,8 +24,18 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; -using AvaloniaEdit.Text; -using Avalonia.Layout; +using AvaloniaEdit.Document; +using AvaloniaEdit.Indentation; +using AvaloniaEdit.Rendering; +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 { @@ -101,6 +99,11 @@ namespace AvaloniaEdit.Editing DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; + + textView.GetObservableWithHistory(TextBlock.FontSizeProperty).Subscribe(fontSizeChange => + { + TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); + }); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
17
Merge pull request #39 from danwalmsley/update-avalonia
14
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057542
<NME> buster.js <BEF> ADDFILE <MSG> Merge pull request #2 from SamGiles/master Add example buster test <DFF> @@ -0,0 +1,12 @@ +var config = module.exports; + +config["FruitMachineTests"] = { + rootPath: '../', + environment: "browser", + sources: [ + 'lib/fruitmachine.js' + ], + tests: [ + 'test/fruitmachine_test.js' + ] +};
12
Merge pull request #2 from SamGiles/master
0
.js
js
mit
ftlabs/fruitmachine
10057543
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057544
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057545
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057546
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057547
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057548
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057549
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { Open(); Height = double.NaN; MinHeight = 0; UpdatePosition(); } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Merge pull request #215 from whistyun/fix-completionwindow-wrongpos fix the wrong complete window position <DFF> @@ -76,15 +76,20 @@ namespace AvaloniaEdit.CodeCompletion /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() - { + { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; - + AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; - + + PlacementTarget = TextArea.TextView; + PlacementMode = PlacementMode.AnchorAndGravity; + PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; + PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; + //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); @@ -113,11 +118,11 @@ namespace AvaloniaEdit.CodeCompletion public void Show() { + UpdatePosition(); + Open(); Height = double.NaN; MinHeight = 0; - - UpdatePosition(); } public void Hide() @@ -206,7 +211,7 @@ namespace AvaloniaEdit.CodeCompletion base.Detach(); Window.Hide(); } - + public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open @@ -372,7 +377,8 @@ namespace AvaloniaEdit.CodeCompletion var position = _visualLocation - textView.ScrollOffset; - Host?.ConfigurePosition(textView, PlacementMode.AnchorAndGravity, position, Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft, Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight); + this.HorizontalOffset = position.X; + this.VerticalOffset = position.Y; } // TODO: check if needed
13
Merge pull request #215 from whistyun/fix-completionwindow-wrongpos
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit